复制代码 代码如下:
string ProviderName = "System.Data.SqlClient";
string ConnStr = "Data Source=.;Initial Catalog=Northind;Integrated Security=True";
string sqlStr = "select * from dbo.Categories";
复制代码 代码如下:
public void getSqlConnection()
{
//得到一个数据提供者,根据其传入的数据提供者对象
DbProviderFactory dbf = DbProviderFactories.GetFactory(ProviderName);
//创建连接
DbConnection conn = dbf.CreateConnection();
//连接字符串
conn.ConnectionString = ConnStr;
conn.Open();
DbTransaction ts = conn.BeginTransaction();
DbCommand dbcmd = null;
try
{
dbcmd = dbf.CreateCommand();
dbcmd.CommandText = sqlStr;
dbcmd.Connection = conn;
dbcmd.Transaction = ts;
DbDataReader dr = dbcmd.ExecuteReader();
while (dr.Read())
{
Console.WriteLine(dr[1].ToString());
}
dr.Close();
ts.Commit();
}
catch (Exception e)
{
ts.Rollback();
}
finally
{
conn.Close();
if (dbcmd != null)
{
dbcmd.Dispose();
}
}
}
复制代码 代码如下:
public void getDataSetConnection()
{
//得到一个数据提供者,根据其传入的数据提供者对象
DbProviderFactory dbf = DbProviderFactories.GetFactory(ProviderName);
//创建连接
DbConnection conn = dbf.CreateConnection();
//连接字符串
conn.ConnectionString = ConnStr;
//创建DataAdapter对象
DbDataAdapter da = dbf.CreateDataAdapter();
//创建自动生成sql语句对象
DbCommandBuilder dbCmdb = dbf.CreateCommandBuilder();
using (DbCommand dbcmd = dbf.CreateCommand())
{
dbcmd.CommandText = sqlStr;
dbcmd.Connection = conn;
//DbDataAdapter指定命令
da.SelectCommand = dbcmd;
//DbCommandBuilder指定dataAdpter
dbCmdb.DataAdapter = da;
DataSet ds = new DataSet();
da.Fill(ds);
// ds.Tables[0].Rows[0].Delete();
da.Update(ds);
DataTable dt = ds.Tables[0];
DataRow dr;
for (int i = 0; i < dt.Rows.Count; i++)
{
dr = dt.Rows[i];
Console.WriteLine(dr[1] + " " + dr[2]);
}
}
}
新闻热点
疑难解答
图片精选