我可以在我的应用程序中多次使用相同的SQL连接字符串吗?

30 浏览
0 Comments

我可以在我的应用程序中多次使用相同的SQL连接字符串吗?

我刚接触SQL。我正在使用C#构建应用程序,该应用程序使用本地SQL Server来读写数据。我只有一个数据库,当我连接到SQL Server时,连接字符串始终是相同的。\n我的项目应用程序中有9个窗体,每个窗体都使用相同的连接字符串,在某些窗体中我多次使用相同的连接。我可以在同一个窗体中多次使用相同的连接字符串吗?谢谢。\n以下是连接字符串:\nSqlConnection cn = new SqlConnection(@\"Data Source=localhost; AttachDbFilename=E:\\myDB\\DB1.mdf; trusted_connection=yes\"

0
0 Comments

可以在应用程序中多次使用相同的SQL连接字符串。最佳方法是在web.configapp.config中定义连接字符串,然后在应用程序中读取它们,如下所示:

System.Configuration.ConfigurationManager.ConnectionStrings["CS"].ConnectionString

<connectionStrings>
    <add name="CS" connectionString="Data Source=localhost; AttachDbFilename=E:\myDB\DB1.mdf; trusted_connection=yes" providerName="System.Data.SqlClient"/>
</connectionStrings>

0
0 Comments

在应用程序中多次使用相同的SQL连接字符串可能会导致一些问题。为了解决这个问题,可以将所有的数据操作从表单中移除,并将这些操作放在一个处理数据操作的类中。此外,建议为每个方法使用一个连接,使每个方法的连接共享连接字符串。下面是一个示例代码,用于说明如何使用连接字符串:

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 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 = "", SqlDbType = SqlDbType.NVarChar });
                        cmd.Parameters[""].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();
                            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 = "", SqlDbType = SqlDbType.NVarChar });
                        cmd.Parameters.Add(new SqlParameter { ParameterName = "", SqlDbType = SqlDbType.NVarChar });
                        cmd.Parameters.Add(new SqlParameter { ParameterName = "", SqlDbType = SqlDbType.NVarChar });
                        cmd.Parameters.Add(new SqlParameter { ParameterName = "", SqlDbType = SqlDbType.Int, Direction = ParameterDirection.Output });
                        cmd.Parameters[""].Value = CompanyName;
                        cmd.Parameters[""].Value = ContactName;
                        cmd.Parameters[""].Value = ContactTitle;
                        cn.Open();
                        var affected = cmd.ExecuteScalar();
                        this.Exception = null;
                        return Convert.ToInt32(cmd.Parameters[""].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 = "", SqlDbType = SqlDbType.Int });
                    cmd.Parameters.Add(new SqlParameter { ParameterName = "", SqlDbType = SqlDbType.Bit, Direction = ParameterDirection.Output });
                    cmd.Parameters[""].Value = Indentifier;
                    cmd.Parameters[""].Value = 0;
                    try
                    {
                        cn.Open();
                        var affected = cmd.ExecuteNonQuery();
                        this.Exception = null;
                        if (Convert.ToBoolean(cmd.Parameters[""].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 = "", SqlDbType = SqlDbType.NVarChar });
                        cmd.Parameters.Add(new SqlParameter { ParameterName = "", SqlDbType = SqlDbType.NVarChar });
                        cmd.Parameters.Add(new SqlParameter { ParameterName = "", SqlDbType = SqlDbType.NVarChar });
                        cmd.Parameters.Add(new SqlParameter { ParameterName = "", SqlDbType = SqlDbType.Int });
                        cmd.Parameters.Add(new SqlParameter { ParameterName = "", SqlDbType = SqlDbType.Bit, Direction = ParameterDirection.Output });
                        cmd.Parameters[""].Value = CompanyName;
                        cmd.Parameters[""].Value = ContactName;
                        cmd.Parameters[""].Value = ContactTitle;
                        cmd.Parameters[""].Value = PrimaryKey;
                        cmd.Parameters[""].Value = 0;
                        cn.Open();
                        var affected = cmd.ExecuteNonQuery();
                        this.Exception = null;
                        if (Convert.ToBoolean(cmd.Parameters[""].Value))
                        {
                            return true;
                        }
                        else
                        {
                            return false;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                this.Exception = ex;
                return false;
            }
        }
    }
}

通过将数据操作封装在一个类中,并为每个方法使用独立的连接,可以避免在应用程序中多次使用相同的SQL连接字符串造成的问题。这样可以提高资源利用率,并且只在需要进行操作的时候才打开连接。

0
0 Comments

可以在web.config文件或者app.config文件(在Windows表单应用程序中)中存储相同的连接字符串,并且可以重复使用它。

System.Configuration.ConfigurationManager.ConnectionStrings["connectionStringName"].ConnectionString;

其中,connectionStringName是存储在web.config文件中的连接字符串的名称。

如果是Windows表单应用程序,可以参考以下链接中的内容来使用app.config文件:stackoverflow.com/questions/114527/…

0