我想通过数据库将值存储在数据表中,并将其与文本框中的值进行比较,但我在连接字符串附近遇到无法识别的转义序列错误。我尝试过给出链接的技术---> [CS1009: Unrecognized escape sequence。 但是这没有用,因为我会得到一个名为无法识别的路径的异常。请告诉我们。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
using System.Drawing;
using System.Data;
public partial class searchsale : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
try
{
SqlConnection conn = new SqlConnection("Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\rdb.mdf;Integrated Security=True;User Instance=True");
conn.Open();
string scriptname = TextBox1.Text;
string accnum = TextBox2.Text;
string sql = @"select scriptname,accnum,Quantity,price from transac where scriptname = @sn, accnum = @an and transactio = 'Sell'";
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = sql;
cmd.Parameters.AddWithValue("@an", accnum);
cmd.Parameters.AddWithValue("@sn", scriptname);
SqlDataReader dr = cmd.ExecuteReader();
DataTable dt = GetDataTable(sql);
}
catch (Exception ex)
{
Response.Write("error" + ex.ToString());
}
}
private DataTable GetDataTable (string sql)
{
DataTable dt = new DataTable();
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ToString()))
{
SqlDataAdapter da = new SqlDataAdapter(sql, conn);
da.Fill(dt);
}
return dt;
}
}
答案 0 :(得分:4)
变化:
"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\rdb.mdf;Integrated Security=True;User Instance=True"
要
@"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\rdb.mdf;Integrated Security=True;User Instance=True"
或者
"Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\rdb.mdf;Integrated Security=True;User Instance=True"
检查this link有关C#中转义序列的信息。
字符串前面的@
使得它不会执行任何转义字符。
答案 1 :(得分:3)
在连接字符串之前使用逐字@
,如
SqlConnection conn = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\rdb.mdf;Integrated Security=True;User Instance=True");