C# 我可以在应用程序中多次使用相同的SQL连接字符串吗?
我是SQL新手。我正在使用C#构建应用程序,C#使用本地SQL Server读取/写入数据。我只有一个数据库,当我连接到SQL Server时,连接字符串总是相同的 我的项目应用程序中有9个windows窗体,每个窗体使用相同的连接字符串,在某些窗体中,我多次使用相同的连接。我可以在同一表单中多次使用同一连接字符串吗?多谢各位 以下是连接字符串:C# 我可以在应用程序中多次使用相同的SQL连接字符串吗?,c#,sql,C#,Sql,我是SQL新手。我正在使用C#构建应用程序,C#使用本地SQL Server读取/写入数据。我只有一个数据库,当我连接到SQL Server时,连接字符串总是相同的 我的项目应用程序中有9个windows窗体,每个窗体使用相同的连接字符串,在某些窗体中,我多次使用相同的连接。我可以在同一表单中多次使用同一连接字符串吗?多谢各位 以下是连接字符串: SqlConnection cn = new SqlConnection(@"Data Source=localhost; AttachDbFilen
SqlConnection cn = new SqlConnection(@"Data Source=localhost; AttachDbFilename=E:\myDB\DB1.mdf; trusted_connection=yes
是的,对于windows窗体应用程序,您可以将其存储在web.config文件或app.config文件中,然后重新使用
System.Configuration.ConfigurationManager.
ConnectionStrings["connectionStringName"].ConnectionString;
其中connectionStringName是存储在web.config文件中的连接字符串的名称是的,您当然可以,最好的方法是在
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>
System.Configuration.ConfigurationManager.connSectionString[“CS”].connestinString
背后有一个相当智能的机制:。连接保持可用一段时间。如果您再次需要连接,并且传入了完全相同的连接字符串(区分大小写),则将重复使用相同的连接
这意味着:
- 是的,您可以在应用程序中使用一个“全局”连接
- 在大多数情况下都不会有什么不同:-)
是的,你可以。尽管您可能希望寻找不必一直重复代码的方法,但是如果连接字符串发生更改,您只需更改一次,而不是多次。一种方法是将连接字符串放在配置文件中。您可以有一个带有连接字符串的类的静态实例,也可以有一个简单的连接工厂
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);
}
}
未测试,因此可能有一些语法错误。这是最好的策略: 在应用程序中,使用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();
}
可以对所有数据操作使用一个连接,但更好的方法是从表单中删除所有数据操作,并将这些操作放在处理数据操作的类中。此外,我还建议对每个方法使用连接,因为每个方法连接共享连接字符串。下面是我为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;
}
}
}
}
使用系统;
使用System.Collections.Generic;
使用系统数据;
使用System.Data.SqlClient;
命名空间数据操作
{
公共类后台操作
{
公共字符串连接字符串{get;set;}
公共数据表{get;set;}
公共列表联系人标题{get;set;}
公共异常{get;set;}
公共图书馆有例外
{
得到
{
返回此。异常!=null;
}
}
公共档案检索所有记录()
{
this.DataTable=新的DataTable();
尝试
{
使用(SqlConnection cn=newsqlconnection{ConnectionString=this.ConnectionString})
{
使用(SqlCommand cmd=newsqlcommand{Connection=cn,CommandType=CommandType.StoredProcedure,CommandText=“dbo.[SelectAllCustomers]”)
{
尝试
{
cn.Open();
}
捕获(SqlException sqlex)
{
if(sqlex.Message.Contains(“无法打开连接”))
{
this.Exception=sqlex;
返回false;
}
}
Load(cmd.ExecuteReader());
}
}
如果(ContactTitles==null)
{
RetrieveContactTitles();
}
this.Exception=null;
返回true;
}
捕获(例外情况除外)
{
这个.Exception=ex;
返回false;
}
}
public bool RetrieveAllRecordsbyContactTitle(字符串联系人类型)
{
this.DataTable=新的DataTable();
尝试
{
使用(SqlConnection cn=newsqlconnection{ConnectionString=this.ConnectionString})
{
使用(SqlCommand cmd=newsqlcommand{Connection=cn,CommandType=CommandType.StoredProcedure,CommandText=“dbo.ContactByType”})
{
Add(新的SqlParameter{ParameterName=“@ContactTitleType”,SqlDbType=SqlDbType.NVarChar});
cmd.Parameters[“@ContactTitleType”]。Value=contactType;
cn.Open();
Load(cmd.ExecuteReader());
}
}
this.Exception=null;
返回true;
}
捕获(例外情况除外)
{
这个.Exception=ex;
返回false;
}
}
公共bool RetrieveContactTitles()
{
如果(ContactTitles!=null)
{
返回true;
}
尝试
{
使用(SqlConn)
<?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;