【发布时间】:2015-07-06 17:39:15
【问题描述】:
所以我正在制作一个提交内容页面,它将用户输入存储到数据库中,这是我目前拥有的代码:
protected void submitData_Click(object sender, EventArgs e)
{
string userId = HttpContext.Current.User.Identity.Name;
int categoryId = Convert.ToInt32(categories.SelectedValue);
if (categoryId > 0 && content.Text != "" && description.Text != "")
{
using (SqlConnection connection = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename="C: \Users\Will\Documents\Visual Studio 2015\WebSites\inshort\App_Data\ASPNETDB.MDF";Integrated Security=True"))
{
SqlCommand cmd = new SqlCommand("INSERT INTO aspnet_newscontent (author, username, date, category, content, description) VALUES (@author, @username, @date, @category, @content, @description)");
cmd.CommandType = System.Data.CommandType.Text;
cmd.Connection = connection;
cmd.Parameters.AddWithValue("@author", nameInput.Text);
cmd.Parameters.AddWithValue("@username", userId);
cmd.Parameters.AddWithValue("@date", DateTime.Today);
cmd.Parameters.AddWithValue("@category", categoryId);
cmd.Parameters.AddWithValue("@content", content.Text);
cmd.Parameters.AddWithValue("@description", description.Text);
connection.Open();
cmd.ExecuteNonQuery();
}
}
else
{
errorLabel.Text = "Please fill in the required fields.";
}
}
但是,我收到一条错误消息,指出连接字符串包含无效字符“\”,这是有道理的,但是每当我转到数据库的属性并查看连接字符串属性时,它就是这么说的。
如果有任何更改,我正在使用 Microsoft Sql Server Express 将数据库托管在本地。有人知道如何格式化这些连接字符串吗?
【问题讨论】:
-
转义字符串中的双引号,对于逐字字符串,使用双 double 引号,例如
@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=""C: \Users\Will\Documents\Visual Studio 2015\WebSites\inshort\App_Data\ASPNETDB.MDF"";Integrated Security=True"-- 投票关闭为错字 -
这篇文章可能会帮助有类似问题的人学习如何正确使用转义字符。
-
也有很多关于这个的帖子,这个问题可以被认为是stackoverflow.com/questions/1928909/…的副本
标签: c# sql asp.net sql-server connection-string