[英]About connecting sql server to c# (with ADO.NET)
我在将数据库连接到连接字符串部分中的c#时遇到问题,这是我的代码,但是当我运行它时,出现以下错误:
“初始化字符串的格式不符合从索引84开始的规范”
我的代码:
private void button2_Click(object sender, EventArgs e)
{
SqlConnection Cn = new SqlConnection(@" Server=TheAddress ; Database=MyDataBase.mdf ; integrated security='True' @");
Cn.Open();
SqlCommand Cm = new SqlCommand("", Cn);
Cm.CommandText = "INSERT INTO Table1(ID_Food, Name_Food , TypeOfService_Food , Price_Food , Type_Food) VALUES (@ID_Food , @Name_Food , @TypeOfService_Food , @Price_Food , @Type_Food)";
Cm.Parameters.AddWithValue("@ID_Food", textBox1.Text);
Cm.Parameters.AddWithValue("@Name_Food", textBox2.Text);
Cm.Parameters.AddWithValue("@TypeOfService_Food", textBox3.Text);
Cm.Parameters.AddWithValue("@Price_Food", textBox4.Text);
Cm.Parameters.AddWithValue("@Type_Food", textBox5.Text);
Cm.ExecuteNonQuery();
Cn.Close();
}
我什至无法打开我的连接(在声明SqlConnection时发生错误),我知道这是一个过时的问题……但是,这让我很生气(我无法正确设置它)(使用Visual Studio 2012和sqlserver Management Studio 2012)
看起来您应该从连接字符串中删除结尾处的“ @”。 您还可以在创建SqlConnection和SqlCommand对象时考虑使用using语句,以便正确处理它们。
using (var Cn = new SqlConnection(@"Server=TheAddress;Database=MyDataBase.mdf;integrated security=True"))
{
Cn.Open();
using (var Cm = new SqlCommand("", Cn))
{
Cm.CommandText = "INSERT INTO Table1(ID_Food, Name_Food , TypeOfService_Food , Price_Food , Type_Food) VALUES (@ID_Food , @Name_Food , @TypeOfService_Food , @Price_Food , @Type_Food)";
Cm.Parameters.AddWithValue("@ID_Food", textBox1.Text);
Cm.Parameters.AddWithValue("@Name_Food", textBox2.Text);
Cm.Parameters.AddWithValue("@TypeOfService_Food", textBox3.Text);
Cm.Parameters.AddWithValue("@Price_Food", textBox4.Text);
Cm.Parameters.AddWithValue("@Type_Food", textBox5.Text);
Cm.ExecuteNonQuery();
Cn.Close();
}
}
您需要提供有效的connection string
。
尝试这个 :
SqlConnection Cn = new SqlConnection(@"Data Source=TheAddress;Initial Catalog=MyDataBase.mdf;Integrated Security=True");
编辑:来自评论:随着您获得运行时专有信息,请检查您是否能够与服务器通信。
在这里检查
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.