1、連接字符串
1)直接配置數據源的時候,保存鏈接字符串
2)在項目設計器中“設置”中添加鏈接字符串
在app中將會有
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
</configSections>
<connectionStrings>
<add name="WindowsApplication3.Properties.Settings.MYSALEDBConnectionString"
connectionString="Data Source=computer;Initial Catalog=MYSALEDB;User ID=sa;Password=123456"
providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
在讀取的鏈接字符串的時候
添加using System.Configuration;及引用
System.Configuration.ConfigurationManager.ConnectionStrings["WindowsApplication3.Properties.Settings.MYSALEDBConnectionString"].ToString()
即可得到連接字符串
2、命令處理數據(sqltext)
1)只返回數據的情況,用dataread,將dataread綁定到datagridview有兩種方法
private void GetData()
{
try
{
using (SqlConnection connection = new SqlConnection(sqlStr))
{
string strSql = "select * from 採購客戶 where 1=1 ";
if (this.txtCustomerName.Text != string.Empty)
{
strSql += " and 客戶名稱 like '%" + this.txtCustomerName.Text.Replace("'", "").Replace("/"", "") + "%'";
}
if (connection.State != ConnectionState.Connecting) connection.Open();
SqlCommand command = new SqlCommand(strSql, connection);
SqlDataReader reader = command.ExecuteReader(CommandBehavior.CloseConnection);
DataTable dt = new DataTable();
dt.Load(reader);
dgvData.DataSource = dt;
//this.bindingSource1.DataSource = reader;
//dgvData.DataSource = bindingSource1;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
關於創建command,有很多方法:
1、SqlCommand command=new SqlCommand(sqltext,connection);
2、SqlCommand command = connection.CreateCommand();
command.CommandText = sqltext;
存儲過程:帶參數
Create PROCEDURE GetCutomer
@customerName nvarchar(20)
/*
(
@parameter1 int = 5,
@parameter2 datatype OUTPUT
)
*/
AS
if(@customerName<>'')
select * from [採購客戶] where 客戶名稱 like '%'+@customerName+'%'
else
select * from [採購客戶]
RETURN
private void GetDataProcedure()
{
try
{
using (SqlConnection connection = new SqlConnection(sqlStr))
{
if (connection.State != ConnectionState.Connecting) connection.Open();
SqlCommand command = new SqlCommand("GetCutomer", connection);
command.CommandType = CommandType.StoredProcedure;
string m = "";
if (this.txtCustomerName.Text != string.Empty) m = this.txtCustomerName.Text;
command.Parameters.AddWithValue("@customerName", this.txtCustomerName.Text);
SqlDataReader reader = command.ExecuteReader(CommandBehavior.CloseConnection);
DataTable dt = new DataTable();
dt.Load(reader);
dgvData.DataSource = dt;
//this.bindingSource1.DataSource = reader;
//dgvData.DataSource = bindingSource1;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}