2

I'm trying to connect to database and I get the following error:

Illegal characters in path.

Here is my code:

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();
}

How to do I connect to the database so the I can insert into it?

4

2 回答 2

8

你需要逃跑\targil3.mdf

例如,在分配字符串之前使用\\或放置一个。@

SqlConnection Con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\targil3.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
于 2013-07-29T15:27:00.007 回答
0

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

要么通过使用显式转义这些字符

\\

或者

在赋值之前使用@符号。

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)
    {

    }
 }

您不会遇到上述任何错误。

于 2013-07-29T15:33:14.200 回答