C# ConnectionString属性未初始化为SQL Server
我正在尝试使用SQL Server编写Winforms CRUD操作应用程序,但在运行该程序并执行查询时,出现了一个错误 ConnectionString未初始化 甚至在我将新连接添加到现有数据库并复制连接字符串的精确值之后 我有一门课是这样的:C# ConnectionString属性未初始化为SQL Server,c#,sql-server,winforms,dapper,C#,Sql Server,Winforms,Dapper,我正在尝试使用SQL Server编写Winforms CRUD操作应用程序,但在运行该程序并执行查询时,出现了一个错误 ConnectionString未初始化 甚至在我将新连接添加到现有数据库并复制连接字符串的精确值之后 我有一门课是这样的: public partial class PersonContactForm : Form { // I declared my connect db here SqlConnection sqlCon = new SqlConne
public partial class PersonContactForm : Form
{
// I declared my connect db here
SqlConnection sqlCon = new SqlConnection(@"Data Source=DESKTOP-JIV4OD1\SQLEXPRESS;Initial Catalog=DapperCrud; Integrated);
// some code
// my test db connect. It does work
private void btnTestSqlConn_Click(object sender, EventArgs e)
{
using (sqlCon = new SqlConnection(@"Data Source=DESKTOP-JIV4OD1\SQLEXPRESS;Initial Catalog=DapperCrud; Integrated Security=True;"))
{
try
{
sqlCon.Open();
}
catch(SqlException sqlEx)
{
MessageBox.Show(sqlEx.Message);
}
MessageBox.Show("Connection to SQL Server OK!");
return;
}
}
// this function inserts data into database table. When I clicked on this button.
// the error ConnectionString is not initialized occurred.
private void btnSave_Click(object sender, EventArgs e)
{
try
{
// if sql state is closed so open it
if (sqlCon.State == ConnectionState.Closed)
sqlCon.Open();
DynamicParameters param = new DynamicParameters();
param.Add("@contactId", contactId);
param.Add("@firstName", txbFirstName.Text.Trim());
param.Add("@lastName", txbLastName.Text.Trim());
param.Add("@mobile", txbMobile.Text.Trim());
param.Add("@Address", txbAddress.Text.Trim());
sqlCon.Execute("ContactAddOrEdit", param, commandType: CommandType.StoredProcedure);
// if contactId == 0 then we saved data successfully
if (contactId == 0)
MessageBox.Show("Saved OK!");
else
MessageBox.Show("Updated OK!");
// fill into DataGridView
fillDataGridView();
// clear textBox fields after filled
clear();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
// close sql after executed
sqlCon.Close();
}
}
// .... some code
}
您的连接字符串未关闭。 您有
SqlConnection sqlCon=newsqlconnection(@“数据源=DESKTOP-JIV4OD1\SQLEXPRESS;初始目录=DapperCrud;集成的)。
您需要在末尾用“”
将其关闭
下面是一个链接,它在连接字符串方面对我帮助很大 改为这样做:
将连接字符串保持为类级别的字符串:
public partial class PersonContactForm : Form
{
private string _connStr = @"Data Source=DESKTOP-JIV4OD1\SQLEXPRESS;Initial Catalog=DapperCrud; Integrated Security=True;";
private void btnTestSqlConn_Click(object sender, EventArgs e)
{
using (sqlCon = new SqlConnection(_connStr))
{
sqlCon.ExecuteScalar<string>("SELECT @@version");
MessageBox.Show("Connection to SQL Server OK!");
}
}
private void btnSave_Click(object sender, EventArgs e)
{
try
{
DynamicParameters param = new DynamicParameters();
param.Add("@contactId", contactId);
param.Add("@firstName", txbFirstName.Text.Trim());
param.Add("@lastName", txbLastName.Text.Trim());
param.Add("@mobile", txbMobile.Text.Trim());
param.Add("@Address", txbAddress.Text.Trim());
sqlCon.Execute("ContactAddOrEdit", param, commandType: CommandType.StoredProcedure);
// if contactId == 0 then we saved data successfully
if (contactId == 0)
MessageBox.Show("Saved OK!");
else
MessageBox.Show("Updated OK!");
// fill into DataGridView
fillDataGridView();
// clear textBox fields after filled
clear();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
// .... some code
}
公共部分类PersonContactForm:Form
{
私有字符串\u connStr=@“数据源=DESKTOP-JIV4OD1\SQLEXPRESS;初始目录=DapperCrud;集成安全性=True;”;
私有void btnTestSqlConn\u单击(对象发送方,事件参数e)
{
使用(sqlCon=newsqlconnection(_connStr))
{
sqlCon.ExecuteScalar(“选择@@version”);
Show(“与SQL Server的连接正常!”);
}
}
私有void btnSave\u单击(对象发送方,事件参数e)
{
尝试
{
DynamicParameters param=新的DynamicParameters();
参数添加(“@contactId”,contactId);
param.Add(“@firstName”,txbFirstName.Text.Trim());
param.Add(“@lastName”,txbLastName.Text.Trim());
参数Add(“@mobile”,txbMobile.Text.Trim());
参数Add(“@Address”,txbAddress.Text.Trim());
sqlCon.Execute(“ContactAddOrEdit”,参数,commandType:commandType.StoredProcess);
//如果contactId==0,则我们成功保存了数据
如果(contactId==0)
MessageBox.Show(“保存好!”);
其他的
MessageBox.Show(“更新确定!”);
//填充到DataGridView中
fillDataGridView();
//填充后清除文本框字段
清除();
}
捕获(例外情况除外)
{
MessageBox.Show(例如Message);
}
}
//……一些代码
}
您不需要打开和关闭连接;整洁会为你做的
让存储过程返回0作为它保存的实体的ID是很奇怪的。通常,当db保存某些内容时,您应该让它返回所保存内容的ID(以便您可以将其他数据与之关联)您需要在每个方法中创建一个新的SqlConnection实例,该方法的作用域仅限于该方法。完全删除类字段sqlCon
。在第一个实例中使用using
是正确的,但是每次创建和使用连接实例时都需要这样做。由于作用域和测试按钮的功能与您认为的不同。打开实例后,它将销毁实例范围为sqlCon
。网上有很多关于最佳实践和如何在c#中使用ado.net的操作文章。从这里开始。@Igor您的意思是,对于每个操作,我都需要新建一个SqlConnection??但是我已经看完了教程,看不出有必要这么做。@kapsiR是的,谢谢你提供的内容丰富的帖子!!是的,每次您决定要查询数据库时(例如在按钮单击a和按钮单击B事件上),您都应该创建一个新的SqlConnection实例。它很便宜,因为ado.net将为您汇集实际连接。它确保资源在使用完毕后立即释放。它还可以确保您没有竞争条件(例如,在第一次执行完成之前单击“下一步”按钮),它可以确保不会因为无限期打开的db连接而出现错误,列表还可以继续。@Igor我按照教程做了同样的事,但对此不确定。谢谢你的清楚解释。我已经试过了,它可以正常工作。btnTestSqlConn\u单击
仍然需要打开连接。另外,ExecuteScalar
是SqlCommand
上的功能,而不是SqlConnection
@Igor获得了它。您应该从以下事实开始您的答案:显示的代码是基于dapper的,并且可能提供到nuget包或项目站点的链接。我还将在代码文件中包含using
语句,以便SqlConnection
上的ExecuteScalar
等扩展方法可以工作。但是OP已经在使用Dapper的DynamicParameters类的Dapper并在连接上调用Execute。。(但你是对的,这很微妙。我也为整洁添加了一个标签,谢谢)