C# 为什么我的代码没有';你不能正常工作吗?
我想检查逻辑表中是否存在逻辑名称。我的查询和过程工作正常,但在C#代码中工作不正常。它假设ExecuteShalar()返回0或1,然后我选中它并显示消息框或继续执行其他代码。我的代码如下C# 为什么我的代码没有';你不能正常工作吗?,c#,sql,sql-server,ado.net,C#,Sql,Sql Server,Ado.net,我想检查逻辑表中是否存在逻辑名称。我的查询和过程工作正常,但在C#代码中工作不正常。它假设ExecuteShalar()返回0或1,然后我选中它并显示消息框或继续执行其他代码。我的代码如下 string LogicNameCheck_Query = "exec searchLogicName '{0}'"; LogicNameCheck_Query = string.Format(LogicNameCheck_Query , txtLogicName); SqlC
string LogicNameCheck_Query = "exec searchLogicName '{0}'";
LogicNameCheck_Query = string.Format(LogicNameCheck_Query , txtLogicName);
SqlCommand sc = new SqlCommand();
sc.Connection = sqlConnection1;
sc.CommandText = LogicNameCheck_Query;
if (sqlConnection1.State != ConnectionState.Open)
{
sqlConnection1.Open();
}
int existLogicName = Convert.ToInt32(sc.ExecuteScalar());
MessageBox.Show(existLogicName +"");
if(existLogicName == 1)
{
MessageBox.Show("name is exist");
return;
}
if (sqlConnection1.State != ConnectionState.Closed)
{
sqlConnection1.Close();
}
以下是searchLogicName过程代码:
ALTER procedure [dbo].[searchLogicName]
@LogName varchar(50)
as
IF EXISTS (select * from Logic where LogicName = @LogName)
select 1 else select 0
txtLogicName是一个文本框。如果将其按原样放入字符串格式参数,则返回的是类IE System.Windows.Forms.TextBox的名称,而不是TextBox的内容。内容来自文本属性
但是,您应该更改逻辑以使用参数化查询来避免和分析问题(txtLogicName中的一个引号将打断您的string.Format代码)
其他需要考虑的问题:你不需要执行任何事情。SqlCommand可以直接使用存储过程的名称,前提是您通知它commandtext是StoredProcess的名称。这是使用
第二点要尽快改变。避免保留全局连接对象,然后每次检查它是否打开。只需使用在内部创建的本地SqlConnection变量。这将保证在完成连接后正确关闭和处理连接使用的资源。这样做不会带来任何损失,因为SqlClient类与一个名为什么是txtLogicName?它似乎是一个文本框。@Steve是的,它是
SqlCommand sc = new SqlCommand();
sc.Connection = sqlConnection1;
sc.CommandText = "searchLogicName";
sc.CommandType = CommandType.StoredProcedure;
sc.Parameters.Add("@LogName", SqlDbType.VarChar, 50).Value = txtLogicName.Text;
if (sqlConnection1.State != ConnectionState.Open)
{
sqlConnection1.Open();
}
int existLogicName = Convert.ToInt32(sc.ExecuteScalar());
...