连接到 SQL Server 时出现"Illegal characters in path"错误



我试图连接到数据库,但我得到了以下错误:

路径中存在非法字符。

这是我的代码:

private void button1_Click(object sender, EventArgs e)
{
    SqlConnection Con = new SqlConnection("Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|targil3.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
    SqlDataAdapter adapt = new SqlDataAdapter();
    adapt.InsertCommand = new SqlCommand(" INSERT INTO tblEmployee VALUES (@employeeNumber, @employeePrivateName, @employeeFamilyName ,@city, @street, @houseNo, @phoneNumber, @birthDate, @startWorkingDate)", Con);
    adapt.InsertCommand.Parameters.Add("@employeeNumber", SqlDbType.Char).Value = textBox1.Text;
    adapt.InsertCommand.Parameters.Add("@employeePrivateName", SqlDbType.VarChar).Value = textBox2.Text;
    adapt.InsertCommand.Parameters.Add("@employeeFamilyName", SqlDbType.VarChar).Value = textBox3.Text;
    adapt.InsertCommand.Parameters.Add("@city", SqlDbType.VarChar).Value = textBox4.Text;
    adapt.InsertCommand.Parameters.Add("@street", SqlDbType.VarChar).Value = textBox5.Text;
    adapt.InsertCommand.Parameters.Add("@houseNo", SqlDbType.Int).Value = textBox6.Text;
    adapt.InsertCommand.Parameters.Add("@phoneNumber", SqlDbType.Char).Value = textBox7.Text;
    adapt.InsertCommand.Parameters.Add("@birthDate", SqlDbType.DateTime).Value = Convert.ToDateTime(textBox8.Text);
    adapt.InsertCommand.Parameters.Add("@startWorkingDate", SqlDbType.DateTime).Value = Convert.ToDateTime(textBox8.Text);

    Con.Open();
    adapt.InsertCommand.ExecuteNonQuery();
    Con.Close();
}

如何连接到数据库以便插入?

您需要退出targil3.mdf

例如,使用\或在字符串赋值之前放一个@

SqlConnection Con = new SqlConnection(@"Data Source=.SQLEXPRESS;AttachDbFilename=|DataDirectory|targil3.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");

这是因为连接字符串中有需要转义的字符。为了克服这个问题,你有几个选择。

使用显式转义这些字符

\

分配前使用@符号。

PS:尽管我建议您在app.config中指定连接字符串,并像这样阅读

string conString = System.Configuration.ConfigurationManager.ConnectionStrings["yourConnectionString"].ToString();

你应该考虑的用户

using (SqlConnection sqlConn = new SqlConnection(conString ))
{
   try
   {
        //your sql statements here
    }
   catch (InvalidOperationException)
    {
    }
    catch (SqlException)
    {
    }
    catch (ArgumentException)
    {
    }
 }

您不会面临上面指定的任何错误。

相关内容

最新更新