连接到数据库 - connectionString connect.Open()错误

时间:2014-05-15 10:11:49

标签: c# sql database visual-studio-2013

所以我试图在数据库中运行查询,该数据库从textbox输入搜索数据库表。我的代码是

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace Query
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void employeeBindingNavigatorSaveItem_Click(object sender, EventArgs e)
        {
            this.Validate();
            this.employeeBindingSource.EndEdit();
            this.tableAdapterManager.UpdateAll(this.personnelDataSet);

        }

        private void Form1_Load(object sender, EventArgs e)
        {
            // TODO: This line of code loads data into the 'personnelDataSet.employee' table. You can move, or remove it, as needed.
            this.employeeTableAdapter.Fill(this.personnelDataSet.employee);

        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        string connectionString = "Server=myServerAddress;Database=myDataBase;Trusted_Connection=True;";

        private void btnSearch_Click(object sender, EventArgs e)
        {
            string commandText = "SELECT employeeID, name, position, hourlyPayRate " +
                     "FROM dbo.employee WHERE name LIKE '%'+ @Name + '%'";

            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                //Create a SqlCommand instance
                SqlCommand command = new SqlCommand(commandText, connection);
                //Add the parameter
                command.Parameters.Add("@Name", SqlDbType.VarChar, 20).Value = textBox1.Text;

                //Execute the query
                try
                {
                    connection.Open();
                    command.ExecuteNonQuery();
                }
                catch
                {
                    //Handle excepetion, show message to user...
                    MessageBox.Show("Error bitch!");
                }
                finally
                {
                    connection.Close();
                }
            }
        }
    }
}

当我抓住这个问题时,我可以看到错误发生在connection.Open()。该错误需要一段时间才会发生,这让我想知道string connectionString = "Server=myServerAddress;Database=myDataBase;Trusted_Connection=True;";

是否存在问题

这是我收到的错误:

An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll

4 个答案:

答案 0 :(得分:1)

您需要验证连接字符串。如果Open()抛出SqlException,则连接字符串无效。要使您能够确定所需连接字符串的确切形式,请查看connectionstrings.com

至于为什么异常显示为无法处理,您需要“消耗”异常,如下所示:

try
{
    connection.Open();
    command.ExecuteNonQuery();
}
catch (Exception e)
{
    // Handle excepetion, show message to user...
    MessageBox.Show(e.Message);
}

我希望这会有所帮助。

答案 1 :(得分:0)

检查出来:

  string connectionString = "Server=.\InstanceName;Database=myDataBase;Integrated Security=True;";

另外

string commandText = "SELECT employeeID, name, position, hourlyPayRate 
                     FROM dbo.employee WHERE name LIKE '%@Name%'";

答案 2 :(得分:0)

尝试:

 string connectionString = "Data Source=myServerAddress;Initial Catalog=myDataBase;User id=myUser;Password=myPAss;Connect Timeout=15;Integrated Security=false";

答案 3 :(得分:0)

尝试在事件中声明连接字符串。

另一种方法是通过web.config链接数据库,如下所示:

  <connectionStrings>
    <connectionString="Data Source=(localdb)\v11.0;Initial Catalog=DBName;Integrated Security=True" providerName="System.Data.SqlClient"/>
  </connectionStrings>

然后连接字符串可以是:

string cs = ConfigurationManager.ConnectionStrings["DBName"].ConnectionString;