我也是C#和OOP的新手,我正在创建一个DB类来连接SQL Server。你能帮我创建一个连接函数并解释如何以多种形式重用它吗?我看过http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.aspx的一个函数,但我不确定如何以另一种形式使用它。
此致 Touseef
答案 0 :(得分:2)
using System.Data.SqlClient;
//
// First access the connection string, which may be autogenerated in Visual Studio for you.
//
string connectionString = "Write your sql connection string"
//
// In a using statement, acquire the SqlConnection as a resource.
//
using (SqlConnection con = new SqlConnection(connectionString))
{
//
// Open the SqlConnection.
//
con.Open();
//
// The following code shows how you can use an SqlCommand based on the SqlConnection.
//
using (SqlCommand command = new SqlCommand("SELECT TOP 2 * FROM Dogs1", con))
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
// process it
}
}
}
修改强> 使用此链接获取详细信息教程 http://www.codeproject.com/KB/database/sql_in_csharp.aspx
答案 1 :(得分:0)
利用:C#: Microsoft Enterprise Library: Data Access
要在第二个表单上建立连接,您需要关闭第一个连接,然后在另一个连接上创建新连接以获取数据。
答案 2 :(得分:0)
Here are few code samples to get you going :
Establish the connection with SQL
string connectionString = "Data Source=myServerAddress;Initial Catalog=myDataBase;User Id=myUsername;Password=myPassword;";
SqlConnection con = new SqlConnection(connectionString);
con.Open();
//Database operations
con.Close();
Fetch the data from Database :
string queryString = "SELECT Column1, Column2 FROM TableName";
SqlDataAdapter adapter = new SqlDataAdapter(queryString, connection);
DataSet customers = new DataSet();
adapter.Fill(customers, "myTable");
Hope this gets you going. All the best.
答案 3 :(得分:0)
如果您指的是DbConnection类(位于System.Data.Common命名空间中),则在C#程序中使用它的一种方法如下:
string CnnStr = "Data Source=local;Initial Catalog=dbTest;User Id=sa;pwd=1";
DbConnection cnn = new SqlConnection(CnnStr);
cnn.Open();