C#数据库操作的用法

2019-12-30 10:56:57王冬梅
  • //the same as: int keywordid = (int)sqlDataReader["KeywordID"]   string keywordName = (string)sqlDataReader[1];  
  • //the same as: string keywordName = (int)sqlDataReader["KeywordName"]   Console.WriteLine("KeywordID = " + keywordid + " , KeywordName = " + keywordName);  
  • }   sqlDataReader.Close();  
  • sqlCommand.Dispose();   sqlConnection.Close();  
  • }   public void UseSqlStoredProcedure()  
  • {   SqlConnection sqlConnection = new SqlConnection(sqlConnectionCommand);  
  • SqlCommand sqlCommand = new SqlCommand();   sqlCommand.CommandType = CommandType.StoredProcedure;  
  • sqlCommand.Connection = sqlConnection;   sqlCommand.CommandText = storedProcedureName;  
  • sqlConnection.Open();   sqlCommand.ExecuteNonQuery();  
  • //you can use reader here,too.as long as you modify the sp and let it like select * from ....   sqlCommand.Dispose();  
  • sqlConnection.Close();   }  
  • public void UseSqlDataSet()   {  
  • SqlConnection sqlConnection = new SqlConnection(sqlConnectionCommand);   SqlCommand sqlCommand = new SqlCommand();  
  • sqlCommand.CommandType = System.Data.CommandType.Text;   sqlCommand.Connection = sqlConnection;  
  • sqlCommand.CommandText = sqlSelectCommand;   sqlConnection.Open();  
  • SqlDataAdapter sqlDataAdapter = new SqlDataAdapter();   sqlDataAdapter.SelectCommand = sqlCommand;  
  • DataSet dataSet = new DataSet();   //sqlCommandBuilder is for update the dataset to database  
  • SqlCommandBuilder sqlCommandBuilder = new SqlCommandBuilder(sqlDataAdapter);   sqlDataAdapter.Fill(dataSet, dataTableName);  
  • //Do something to dataset then you can update it to  Database.Here I just add a row   DataRow row = dataSet.Tables[0].NewRow();