C#数据库操作的三种经典用法
发布日期:2021-05-07 10:36:27 浏览次数:21 分类:精选文章

本文共 3104 字,大约阅读时间需要 10 分钟。

C#?SQL Server 2005??????????????

???????C#?SQL Server 2005?????????????????????????????????????????????? DataSet ????????

?????????

using System;

using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;

namespace DatabaseOperate

{
class SqlOperateInfo
{
// ??????? "aa"?????? "bb"????? "cc"???? "dd"
private string sqlConnectionCommand = "Data Source=aa;Initial Catalog=bb;User ID=cc;Pwd=dd";
private string dataTableName = "Basic_Keyword_Test";
private string storedProcedureName = "Sp_InertToBasic_Keyword_Test";
private string sqlSelectCommand = "Select KeywordID, KeywordName From Basic_Keyword_Test";
private string sqlUpdateCommand = "Delete From Basic_Keyword_Test Where KeywordID = 1";

public void UseSqlReader()  
{
SqlConnection sqlConnection = new SqlConnection(sqlConnectionCommand);
SqlCommand sqlCommand = new SqlCommand();
sqlCommand.CommandType = CommandType.Text;
sqlCommand.Connection = sqlConnection;
sqlCommand.CommandText = sqlSelectCommand;
sqlConnection.Open();
SqlDataReader sqlDataReader = sqlCommand.ExecuteReader();
while (sqlDataReader.Read())
{
int keywordid = (int)sqlDataReader[0];
string keywordName = (string)sqlDataReader[1];
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();
sqlCommand.Dispose();
sqlConnection.Close();
}
public void UseSqlDataSet()
{
SqlConnection sqlConnection = new SqlConnection(sqlConnectionCommand);
SqlCommand sqlCommand = new SqlCommand();
sqlCommand.CommandType = CommandType.Text;
sqlCommand.Connection = sqlConnection;
sqlCommand.CommandText = sqlSelectCommand;
sqlConnection.Open();
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter();
sqlDataAdapter.SelectCommand = sqlCommand;
DataSet dataSet = new DataSet();
SqlCommandBuilder sqlCommandBuilder = new SqlCommandBuilder(sqlDataAdapter);
sqlDataAdapter.Fill(dataSet, dataTableName);
// ?????????????????
DataRow row = dataSet.Tables[0].NewRow();
row[0] = 10000;
row[1] = "new row";
dataSet.Tables[0].Rows.Add(row);
sqlDataAdapter.Update(dataSet, dataTableName);
sqlCommand.Dispose();
sqlDataAdapter.Dispose();
sqlConnection.Close();
}
}

}

???????C#?SQL Server 2005????????????????????????????????DataSet??????????????????????????????????????

上一篇:C#实现读写Binary
下一篇:C#带符号的计算器

发表评论

最新留言

路过,博主的博客真漂亮。。
[***.116.15.85]2025年05月03日 12时42分02秒