我有一个表格,可以在添加之前检查值是否在数据库中。每个字段都在另一个表中,为了保持一切清洁,我为每个字段都有一个checkExists
方法。有没有一种方法可以使用单独的方法连接到数据库,以便我不必在每个字段中连接?
我想做这样的事情,以使我的代码不那么混乱:
public void SetConnection()
{
SqlConnection myConnection =
new SqlConnection("user id=[username];" +
"password=[password];" +
"server=[server];" +
"database=[db_name];");
try
{
myConnection.Open();
}
catch(Exception e)
{
Console.WriteLine("Unable to Connect");
}
}
public Boolean CheckData_Company(string[] items)
{
Class_DB set_conn = new Class_DB();
try
{
set_conn.SetConnection();
}
catch(Exception e)
{
Console.WriteLine(e.ToString());
}
//check that item does not already exist
string query_string = "SELECT * FROM CR_Company WHERE ([CompanyName] = @companyName";
SqlCommand check_Company = new SqlCommand(query_string, set_conn);
check_Company.Parameters.AddWithValue("@CompanyName", items[0]);
int CompanyExist = (int)check_Company.ExecuteScalar();
if(CompanyExist > 0)
{
return true;
}
else
{
return false;
}
}
但我得到了
本地变量set_conn
参数2:无法将class_db转换为system.data.sqlclient.sqlconnection
我理解错误,那么我该怎么做才能返回正确的值,或者我必须在CheckData_Comany()
方法中建立连接?
您的方法SetConnection
应该像:
SqlConnection
public SqlConnection SetConnection()
{
SqlConnection myConnection = new SqlConnection("user id=[username];" +
"password=[password];" +
"server=[server];" +
"database=[db_name];");
try
{
myConnection.Open();
}
catch(Exception e)
{
Console.WriteLine("Unable to Connect");
}
return myConnection;
}
然后您可以拥有类似的东西:
SqlConnection connection = set_conn.SetConnection();
然后将其传递到SqlCommand
构造函数中,作为参数:
SqlCommand check_Company = new SqlCommand(query_string, connection);
您的完整方法实现将成为:
public Boolean CheckData_Company(string[] items)
{
bool Exists = false;
Class_DB set_conn = new Class_DB();
SqlConnection connection = null;
try
{
connection = set_conn.SetConnection();
//check that item does not already exist
string query_string = "SELECT * FROM CR_Company WHERE ([CompanyName] = @companyName";
SqlCommand check_Company = new SqlCommand(query_string, set_conn);
check_Company.Parameters.AddWithValue("@CompanyName", items[0]);
int CompanyExist = (int)check_Company.ExecuteScalar();
if(CompanyExist > 0)
Exists = true;
}
catch(Exception e)
{
Console.WriteLine(e.ToString());
}
finally
{
connection.Close();
}
return Exists;
}
重要的是要注意的是,不要忘记连接连接,最终通过调用connection.Close()
,否则可能会导致饮食来查询数据库时不应发生的资源,我们应该释放所占用的资源。