第一步是添加 SQL 客户端命名空间:
using System.Data.SqlClient;
数据库连接
然后我们创建一个SqlConnection并指定连接字符串。
SqlConnection myConnection = new SqlConnection("user id=username;" +
"password=password;server=serverurl;" +
"Trusted_Connection=yes;" +
"database=database; " +
"connection timeout=30");
这是连接的最后一部分,只需通过以下方式执行(请记住首先确保您的连接有一个连接字符串):
try
{
myConnection.Open();
}
catch(Exception e)
{
Console.WriteLine(e.ToString());
}
SqlCommand
一个 SqlCommand 至少需要两个东西来操作。一个命令字符串和一个连接。指定连接有两种方式,如下图所示:
SqlCommand myCommand = new SqlCommand("Command String", myConnection);
// - or -
myCommand.Connection = myConnection;
也可以使用 SqlCommand.CommandText 属性以两种方式指定连接字符串。现在让我们看看我们的第一个 SqlCommand。为了简单起见,这将是一个简单的 INSERT 命令。
SqlCommand myCommand= new SqlCommand("INSERT INTO table (Column1, Column2) " +
"Values ('string', 1)", myConnection);
// - or -
myCommand.CommandText = "INSERT INTO table (Column1, Column2) " +
"Values ('string', 1)";
SqlDataReader
您不仅需要数据阅读器,还需要 SqlCommand。下面的代码演示了如何设置和执行一个简单的阅读器:
try
{
SqlDataReader myReader = null;
SqlCommand myCommand = new SqlCommand("select * from table",
myConnection);
myReader = myCommand.ExecuteReader();
while(myReader.Read())
{
Console.WriteLine(myReader["Column1"].ToString());
Console.WriteLine(myReader["Column2"].ToString());
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}