所以我试图在数据库中运行查询,从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();
}
}
}
}
}
当我把catch拿出来时,我可以看到错误发生在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
您需要验证连接字符串。如果Open()
抛出SqlException
,则连接字符串无效。为了使您能够建立所需的连接字符串的确切形式,请查看connectionstrings.com。
至于为什么异常显示为unhand,你需要像下面这样"消费"异常:
try
{
connection.Open();
command.ExecuteNonQuery();
}
catch (Exception e)
{
// Handle excepetion, show message to user...
MessageBox.Show(e.Message);
}
看看这个:
string connectionString = "Server=.InstanceName;Database=myDataBase;Integrated Security=True;";
也string commandText = "SELECT employeeID, name, position, hourlyPayRate
FROM dbo.employee WHERE name LIKE '%@Name%'";
try:
string connectionString = "Data Source=myServerAddress;Initial Catalog=myDataBase;User id=myUser;Password=myPAss;Connect Timeout=15;Integrated Security=false";
尝试在事件中声明您的连接字符串。
另一种方法是通过web链接数据库。配置如下:
<connectionStrings>
<connectionString="Data Source=(localdb)v11.0;Initial Catalog=DBName;Integrated Security=True" providerName="System.Data.SqlClient"/>
</connectionStrings>
则连接字符串可以为:
string cs = ConfigurationManager.ConnectionStrings["DBName"].ConnectionString;