user2023203 user2023203 - 7 months ago 41
SQL Question

"Illegal characters in path" error when connecting to SQL Server

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?

Answer

You'll need to escape \targil3.mdf

Use \\ or put an @ before the assignment of the string, for instance.

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