我是SQL新手。我正在使用C#构建应用程序,它使用本地SQL Server来读/写数据。我只有一个数据库,连接到SQL Server时连接字符串始终相同。
我的项目应用程序中有9个窗体,每个窗体使用相同的连接字符串,在某些形式中,我多次使用相同的连接。我可以在同一表单中多次使用相同的连接字符串吗?谢谢
这是连接字符串:
SqlConnection cn = new SqlConnection(@"Data Source=localhost; AttachDbFilename=E:\myDB\DB1.mdf; trusted_connection=yes
答案 0 :(得分:5)
是的,你可以使用它来将它存储在web.config文件或app.config文件中,以防windows表格应用程序然后重复使用
System.Configuration.ConfigurationManager.
ConnectionStrings["connectionStringName"].ConnectionString;
其中connectionStringName是存储在web.config文件中的连接字符串的名称
答案 1 :(得分:3)
您可以使用一个连接进行所有数据操作,但更好的方法是从表单中删除所有数据操作,并将这些操作放在处理数据操作的类中。另外我会建议与上面的每个方法使用连接,每个方法连接共享连接字符串。这是我为MSDN编写的代码示例的示例。请注意,每个方法连接都不是共享的,它是方法的本地连接,并且使用using语句,它将在完成时关闭连接。对于只有重复使用一个连接的应用程序是好的,但是一旦使用更复杂的应用程序与许多用户考虑节省资源并保持连接打开仅足够长的时间用于预期的操作。
概念性例子。
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
namespace DataOperations_cs
{
public class BackendOperations
{
public string ConnectionString { get; set; }
public DataTable DataTable { get; set; }
public List<string> ContactTitles { get; set; }
public Exception Exception { get; set; }
public bool HasException
{
get
{
return this.Exception != null;
}
}
public bool RetrieveAllRecords()
{
this.DataTable = new DataTable();
try
{
using (SqlConnection cn = new SqlConnection { ConnectionString = this.ConnectionString })
{
using (SqlCommand cmd = new SqlCommand { Connection = cn, CommandType = CommandType.StoredProcedure, CommandText = "dbo.[SelectAllCustomers]" })
{
try
{
cn.Open();
}
catch (SqlException sqlex)
{
if (sqlex.Message.Contains("Could not open a connection"))
{
this.Exception = sqlex;
return false;
}
}
this.DataTable.Load(cmd.ExecuteReader());
}
}
if (ContactTitles == null)
{
RetrieveContactTitles();
}
this.Exception = null;
return true;
}
catch (Exception ex)
{
this.Exception = ex;
return false;
}
}
public bool RetrieveAllRecordsbyContactTitle(string contactType)
{
this.DataTable = new DataTable();
try
{
using (SqlConnection cn = new SqlConnection { ConnectionString = this.ConnectionString })
{
using (SqlCommand cmd = new SqlCommand { Connection = cn, CommandType = CommandType.StoredProcedure, CommandText = "dbo.ContactByType" })
{
cmd.Parameters.Add(new SqlParameter { ParameterName = "@ContactTitleType", SqlDbType = SqlDbType.NVarChar });
cmd.Parameters["@ContactTitleType"].Value = contactType;
cn.Open();
this.DataTable.Load(cmd.ExecuteReader());
}
}
this.Exception = null;
return true;
}
catch (Exception ex)
{
this.Exception = ex;
return false;
}
}
public bool RetrieveContactTitles()
{
if (ContactTitles != null)
{
return true;
}
try
{
using (SqlConnection cn = new SqlConnection { ConnectionString = this.ConnectionString })
{
using (SqlCommand cmd = new SqlCommand { Connection = cn, CommandType = CommandType.StoredProcedure, CommandText = "dbo.[SelectContactTitles]" })
{
cn.Open();
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
{
this.ContactTitles = new List<string>();
while (reader.Read())
{
this.ContactTitles.Add(reader.GetString(0));
}
}
}
}
this.Exception = null;
return true;
}
catch (Exception ex)
{
this.Exception = ex;
return false;
}
}
public int AddCustomer(string CompanyName, string ContactName, string ContactTitle)
{
try
{
using (SqlConnection cn = new SqlConnection { ConnectionString = this.ConnectionString })
{
using (SqlCommand cmd = new SqlCommand { Connection = cn, CommandType = CommandType.StoredProcedure, CommandText = "dbo.InsertCustomer" })
{
cmd.Parameters.Add(new SqlParameter { ParameterName = "@CompanyName", SqlDbType = SqlDbType.NVarChar });
cmd.Parameters.Add(new SqlParameter { ParameterName = "@ContactName", SqlDbType = SqlDbType.NVarChar });
cmd.Parameters.Add(new SqlParameter { ParameterName = "@ContactTitle", SqlDbType = SqlDbType.NVarChar });
cmd.Parameters.Add(new SqlParameter { ParameterName = "@Identity", SqlDbType = SqlDbType.Int, Direction = ParameterDirection.Output });
cmd.Parameters["@CompanyName"].Value = CompanyName;
cmd.Parameters["@ContactName"].Value = ContactName;
cmd.Parameters["@ContactTitle"].Value = ContactTitle;
cn.Open();
var affected = cmd.ExecuteScalar();
this.Exception = null;
return Convert.ToInt32(cmd.Parameters["@Identity"].Value);
}
}
}
catch (Exception ex)
{
this.Exception = ex;
return -1;
}
}
public bool RemoveCustomer(int Indentifier)
{
using (SqlConnection cn = new SqlConnection { ConnectionString = this.ConnectionString })
{
using (SqlCommand cmd = new SqlCommand { Connection = cn, CommandType = CommandType.StoredProcedure, CommandText = "dbo.[DeleteCustomer]" })
{
cmd.Parameters.Add(new SqlParameter { ParameterName = "@Identity", SqlDbType = SqlDbType.Int });
cmd.Parameters.Add(new SqlParameter { ParameterName = "@flag", SqlDbType = SqlDbType.Bit, Direction = ParameterDirection.Output });
cmd.Parameters["@Identity"].Value = Indentifier;
cmd.Parameters["@flag"].Value = 0;
try
{
cn.Open();
var affected = cmd.ExecuteNonQuery();
this.Exception = null;
if (Convert.ToBoolean(cmd.Parameters["@flag"].Value))
{
return true;
}
else
{
return false;
}
}
catch (Exception ex)
{
this.Exception = ex;
return false;
}
}
}
}
public bool UpdateCustomer(int PrimaryKey, string CompanyName, string ContactName, string ContactTitle)
{
try
{
using (SqlConnection cn = new SqlConnection { ConnectionString = this.ConnectionString })
{
using (SqlCommand cmd = new SqlCommand { Connection = cn, CommandType = CommandType.StoredProcedure, CommandText = "dbo.[UpateCustomer]" })
{
cmd.Parameters.Add(new SqlParameter { ParameterName = "@CompanyName", SqlDbType = SqlDbType.NVarChar });
cmd.Parameters.Add(new SqlParameter { ParameterName = "@ContactName", SqlDbType = SqlDbType.NVarChar });
cmd.Parameters.Add(new SqlParameter { ParameterName = "@ContactTitle", SqlDbType = SqlDbType.NVarChar });
cmd.Parameters.Add(new SqlParameter { ParameterName = "@Identity", SqlDbType = SqlDbType.Int });
cmd.Parameters.Add(new SqlParameter { ParameterName = "@flag", SqlDbType = SqlDbType.Bit, Direction = ParameterDirection.Output });
cmd.Parameters["@CompanyName"].Value = CompanyName;
cmd.Parameters["@ContactName"].Value = ContactName;
cmd.Parameters["@ContactTitle"].Value = ContactTitle;
cmd.Parameters["@Identity"].Value = PrimaryKey;
cmd.Parameters["@flag"].Value = 0;
cn.Open();
var affected = cmd.ExecuteNonQuery();
this.Exception = null;
if (Convert.ToBoolean(cmd.Parameters["@flag"].Value))
{
return true;
}
else
{
return false;
}
}
}
}
catch (Exception ex)
{
this.Exception = ex;
return false;
}
}
}
}
答案 2 :(得分:2)
是的,你绝对可以,最好的方法是在web.config
或app.config
中定义连接字符串,然后将其读取到您的应用程序,如
System.Configuration.ConfigurationManager.ConnsectionStrings["CS"].ConnestionString
<connectionStrings>
<add name="CS" connectionString="Data Source=localhost; AttachDbFilename=E:\myDB\DB1.mdf; trusted_connection=yes" providerName="Sysem.Data.SqlClient"/>
</connectionStrings>
答案 3 :(得分:2)
背后有一个非常聪明的机制:Connection Pooling。连接仍然可用一段时间。如果您需要再次连接并且传入完全相同的连接字符串(区分大小写),则将重新使用相同的连接。
这意味着:
答案 4 :(得分:2)
是的,你可以。虽然,您可能想要查看不必一直重复代码的方法,但是如果连接字符串发生更改,则只需更改一次,而不是多次。一种方法是在配置文件中使用连接字符串。您可以拥有一个带有连接字符串的类的静态实例,或者一个简单的连接工厂。
public static class ConnectionFactory{
private static string connectionString = "connection string"; //You could get this from config file as other answers suggest.
public static SqlConnection GetConnection(){
return new SqlConnection(connectionString);
}
}
未经测试,可能会出现语法错误。
答案 5 :(得分:2)
这是最好的策略:
在您的应用程序中,使用 getConnection 方法
创建一个静态类public class StaticContext
{
public static SqlConnection getConnessione()
{
string conn = string.Empty;
conn = System.Configuration.ConfigurationManager.ConnectionStrings["connectionStringName"].ConnectionString;
SqlConnection aConnection = new SqlConnection(conn);
return aConnection;
}
}
在您需要连接时的每种形式中,请使用以下方式:
try
{
try
{
conn = StaticContext.getConnessione();
SqlCommand aCommand = new SqlCommand("SELECT.....", conn);
conn.Open();
aReader = aCommand.ExecuteReader();
while (aReader.Read())
{
//TODO
}
}
catch (Exception e)
{
Console.Write(e.Message);
}
}
finally
{
conn.Close();
}
答案 6 :(得分:1)
您要做的是将连接字符串添加到项目解决方案中的 App.Config 或 Web.config (取决于您的项目类型)文件中。它可能看起来像这样:
<?xml version="1.0"?>
<configuration>
<connectionStrings>
<add name="MyConnection"
connectionString="Data Source=localhost; AttachDbFilename=E:\myDB\DB1.mdf; trusted_connection=yes"/>
</connectionStrings>
</configuration>
接下来,您应该包含以下参考:
using System.Configuration;
现在您可以按如下方式获取字符串:
string connectionString = ConfigurationManager.ConnectionStrings["MyConnection"].ConnectionString;
即使在代码中使用ConfigurationManager
,也可能无法找到System.Configuration;
。解决这个问题:
System.Configuration.dll