【发布时间】:2019-02-07 02:48:21
【问题描述】:
我用 C# 创建了一个简单的 Windows 窗体应用程序,现在发现很难将它连接到 SQL Server 数据库。我已经在 Visual Studio 本身中创建了数据库。但是,一旦我尝试插入数据,就会出现 SQL 异常。我的猜测是连接数据源存在问题,即 con 变量。请帮我找到解决方案。
SqlConnection con = new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB;Initial Catalog=Database1;Integrated Security=SSPI");
SqlCommand cmd;
SqlDataAdapter adapt;
if (textBox1.Text != "" && textBox2.Text != "" && textBox3.Text != "")
{
cmd = new SqlCommand("insert into [dbo].[user] (Id, username, password) values (@id, @name, @state)", con);
con.Open();
cmd.Parameters.AddWithValue("@id", textBox1.Text);
cmd.Parameters.AddWithValue("@name", textBox2.Text);
cmd.Parameters.AddWithValue("@state", textBox3.Text);
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Record Inserted Successfully");
}
else
{
MessageBox.Show("Please Provide Details!");
}
数据库文件名是
\WindowsFormsApplication1\WindowsFormsApplication1\Database1.mdf
【问题讨论】:
-
遇到SQL异常时能否提供错误详情?
-
附加信息:无法打开登录请求的数据库“Database1”。登录失败。
标签: c# sql-server winforms