2015-08-23 34 views
0

我的數據庫表包含類似id,姓名,電話,地址,日期等列。 Id會自動增加。如何從文本文件中更新和刪除數據(不包含幾個字)

name=joe|surname=clark|phone=23132131|address=jdsakldjakldja|date=11.02.2015 14:30:45 
    name=betty|surname=ugly|phone=32112121|address=dsadaewqeqrsa|date=11.02.2015 14:30:45 

這是我的INSERT碼

string connStr = @"Data Source=ANLZ\SQLEXPRESS;Initial Catalog=testdb; Trusted_Connection=True;"; 
string createQuery = "INSERT INTO tbl_test(name,surname,phone,address,date) VALUES(@name,@surname,@phone,@address,@date)"; 

SqlConnection conn; 
SqlCommand cmd; 
string[] importfiles = Directory.GetFiles(@"C:\Users\An\Desktop\", "test.txt"); 
     using (conn) 
     { 
      using (cmd = new SqlCommand(createQuery, conn)) 
      { 

       cmd.Parameters.Add("@name", SqlDbType.NVarChar, 50); 
       cmd.Parameters.Add("@surname", SqlDbType.NVarChar, 50); 
       cmd.Parameters.Add("@phone", SqlDbType.NVarChar, 50); 
       cmd.Parameters.Add("@address", SqlDbType.NVarChar, 200); 
       cmd.Parameters.Add("@date", SqlDbType.DateTime); 

       foreach (string importfile in importfiles) 
       { 
        string[] allLines = File.ReadAllLines(importfile); 
        baglanti.Open(); 

        for (int index = 0; index < allLines.Length; index++) 
        { 
         string[] items = allLines[index].Split(new[] { '|' }) 
           .Select(i => i 
           .Split(new[] { '=' })[1]) 
         cmd.Parameters["@name"].Value = items[0]; 
         cmd.Parameters["@surname"].Value = items[1]; 
         cmd.Parameters["@phone"].Value = items[2]; 
         cmd.Parameters["@address"].Value = items[3]; 
         cmd.Parameters["@date"].Value = items[4]; 
         cmd.ExecuteNonQuery(); 
        } 
        conn.Close(); 
       } 
      } 
     } 

我想更新和刪除某些文字到我的數據庫。我也不需要用相同的ID保存相同的記錄。我該怎麼做?

+0

更簡單的方法是使用SQLCommandbuilder。命令生成器執行Select查詢並創建3個附加命令:插入,更新,刪除。然後,您可以使用SQLDataAdapter將數據放入數據表中。當您更改數據表時,您可以使用自動更新數據庫的update()方法。請參閱以下網頁:https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommandbuilder(v=vs.110).aspx – jdweng

回答

0

任何表的ID應具有AUTO_INCREMENT並且是BIGINT或INT類型,並且代碼不會設置ID,SQL Server會這樣做。

要更新,您將創建一個新的SQLCommand並更新類型。

string connStr = @"Data Source=ANLZ\SQLEXPRESS;Initial Catalog=testdb; Trusted_Connection=True;"; 
int updateId = int.Parse(formTextBox.Text); //Or where ever you set the ID to when it is pulled from the database. 
string updateCommand = "UPDATE tbl_test SET [surname][email protected] WHERE ID = @id"; 

using (OleDbConnection conn = new OleDbConnection(connStr)) 
{ 
    using (OleDbCommand comm = new OleDbCommand()) 
    { 
     comm.Connection = conn; 
     comm.CommandText = updateCommand; 
     comm.CommandType = CommandType.Text 
     comm.Parameters.AddWithValue("@surname", items[1]) 
     comm.Parameters.AddWithValue("@id",updateId); 
     try 
     { 
      comm.Open(); 
      conn.ExecuteNonQuery(); 
     } 
     catch(OleDbException ex) 
     { 
      //Do some error catching Messagebox/Email/Database entry 'Or Nothing' 
     } 
    } 
} 

刪除更容易

string connStr = @"Data Source=ANLZ\SQLEXPRESS;Initial Catalog=testdb; Trusted_Connection=True;"; 
int updateId = int.Parse(formTextBox.Text); //Or where ever you set the ID to when it is pulled from the database. 
string deleteComand = "Delete FROM tbl_test WHERE ID = @id"; 

using (OleDbConnection conn = new OleDbConnection(connStr)) 
{ 
    using (OleDbCommand comm = new OleDbCommand()) 
    { 
     comm.Connection = conn; 
     comm.Parameters.AddWithValue("@id", updateId); 
     try 
     { 
      comm.Open(); 
      conn.ExecuteNonQuery(); 
     } 
     catch (OleDbException ex) 
     { 
      //Do some error catching Messagebox/Email/Database entry 'Or Nothing' 
     } 
    } 
} 

幾件事情要注意 - using語句,並嘗試catch塊。

使用將Dispose of和Connection或其他實現了Dispose的對象。

Try Catch將抓取來自執行數據庫調用,無法連接或無法更新行更新的任何錯誤。

我如何更改該更新代碼?

public string updateQuery = "UPDATE tbl_test SET [email protected],[email protected],[email protected],[email protected],[email protected] WHERE [email protected] "; 

// ... 

conn = new SqlConnection(connStr); 
try 
{ 
    string[] importfiles = Directory.GetFiles(@"C:\Users\An\Desktop\", "test.txt"); 

    using (conn) 
    { 
     using (cmd = new SqlCommand(updateQuery, conn)) 
     { 

      cmd.Parameters.Add("@name", SqlDbType.NVarChar, 50); 
      cmd.Parameters.Add("@surname", SqlDbType.NVarChar, 50); 
      cmd.Parameters.Add("@phone", SqlDbType.NVarChar, 50); 
      cmd.Parameters.Add("@address", SqlDbType.NVarChar, 200); 
      cmd.Parameters.Add("@date", SqlDbType.DateTime); 
      cmd.Parameters.Add("@id", SqlDbType.Int); 

      foreach (string importfile in importfiles) 
      { 
       string[] allLines = File.ReadAllLines(importfile); 
       conn.Open(); 

       for (int index = 0; index < allLines.Length; index++) 
       { 
        string[] items = allLines[index].Split(new[] { '|' }) 
         .Select(i => i 
         .Split(new[] { '=' })[1]) 
         .ToArray(); 

        cmd.Parameters["@name"].Value = items[0]; 
        cmd.Parameters["@surname"].Value = items[1]; 
        cmd.Parameters["@phone"].Value = items[2]; 
        cmd.Parameters["@address"].Value = items[3]; 
        cmd.Parameters["@date"].Value = items[4]; 
        cmd.ExecuteNonQuery(); 
       } 
       conn.Close(); 
      } 

     } 
    } 
} 

這是刪除

public string deleteQuery = "DELETE FROM tbl_test WHERE [email protected]"; 

// ... 

conn = new SqlConnection(connStr); 
try 
{ 
    string[] importfiles = Directory.GetFiles(@"C:\Users\An\Desktop\", "test.txt"); 

    using (conn) 
    { 
     using (cmd = new SqlCommand(deleteQuery, baglanti)) 
     { 
      cmd.Parameters.Add("@id", SqlDbType.Int); 

      foreach (string importfile in importfiles) 
      { 
       string[] allLines = File.ReadAllLines(importfile); 
       conn.Open(); 

       for (int index = 0; index < allLines.Length; index++) 
       { 
        string[] items = allLines[index].Split(new[] { '|' }) 
         .Select(i => i 
         .Split(new[] { '=' })[1]) 
         .ToArray(); 

        cmd.Parameters["@name"].Value = items[0]; 
        cmd.Parameters["@surname"].Value = items[1]; 
        cmd.Parameters["@phone"].Value = items[2]; 
        cmd.Parameters["@address"].Value = items[3]; 
        cmd.Parameters["@date"].Value = items[4]; 

        cmd.ExecuteNonQuery(); 
       } 
       conn.Close(); 
      } 
     } 
    } 
} 

對於選擇它是一個涉及多一點。

**public string selectQuery= "Select * FROM tbl_test" ; 
conn = new SqlConnection(connStr); 
try 
{ 
    using (conn) 
    { 
     using (cmd = new SqlCommand(selectQuery, conn)) 
     { 
      using(var dataReader = cmd.ExecuteReader()) 
      { 
       while(datareader.reader()) 
       { 
        //Read the datareader for values and set them . 
        var id = datareader.GetInt32(0); 
       } 
      } 

     } 
    } 
}** 
+0

如何從數據庫中提取id號?該列是auto_increment。我沒有使用文本框 – anilleuss

+0

請參閱更新的答案; – juanvan

+0

它不工作。無論如何ty幫助 – anilleuss

相關問題