簡體   English   中英

連接到SQL Server時出現“路徑中的非法字符”錯誤

[英]“Illegal characters in path” error when connecting to SQL Server

我正在嘗試連接到數據庫,我收到以下錯誤:

路徑中的非法字符。

這是我的代碼:

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

    }
 }

您不會遇到上面指定的任何錯誤。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM