2013-11-25 41 views
-1
using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Windows.Forms; 
using System.Data.SqlClient; 

namespace WindowsFormsApplication1 
{ 
    public partial class Form1 : Form 
    { 
     public Form1() 
     { 
      InitializeComponent(); 
     } 

     private void button2_Click(object sender, EventArgs e) 
     { 
      this.Close(); 
     } 

     private void button1_Click(object sender, EventArgs e) 
     { 
      SqlConnection sc = new SqlConnection(); 
      SqlCommand com = new SqlCommand(); 
      sc.ConnectionString = (@"Data Source=C:\DOCUMENTS AND SETTINGS\SUSAN MANEESH\MY DOCUMENTS\DATA.MDF"); 

       sc.Open(); 
       MessageBox.Show("connect"); 

      com.Connection = sc; 
      com.CommandText = ("INSERT INTO tabletb(name,dept,desig,place)VALUES('" + textBox1.Text + "','" + textBox2.Text + "','" + textBox3.Text + "','" + textBox4.Text + "');"); 

      try 
      { 
       int res = com.ExecuteNonQuery(); 

       if (res > 0) 
       { 
        MessageBox.Show("insert"); 
       } 
      } 
      catch (Exception ex) 
      { 
       MessageBox.Show(ex.Message); 
      } 
      sc.Close(); 




     } 
    } 
} 

此代碼構建成功,但是執行它時。它顯示:「與SQL Server建立連接時發生網絡相關或特定於實例的錯誤。」 請告訴我這是什麼問題。無法從文本框中向數據庫插入值

+0

您應該使用參數,而不是直接在您的SQL命令中注入文本框的文本以防止SQL注入 –

+0

「請告訴我問題是什麼」=>其中一個問題是您要求解決方案, t給出確切的錯誤信息。 –

回答

1

我想你指定錯誤的連接字符串到你的數據庫。

查看有關連接字符串的格式詳細說明here

+0

我很困惑,你會告訴我給出的數據源路徑是否正確 – user3027502

+0

您是否可以使用SQL Management Studio或Visual Studio訪問數據庫? –

0

檢查[的ConnectionStrings] [1],尋找您的供應商和檢查,如果你沒有做你的ConnectionString任何錯誤。

相關問題