2016-12-15 68 views
0

一個DataTable這是我到目前爲止有:麻煩填充從MS SQL表

static void Main(string[] args) 
     { 
      DataTable t = new DataTable(); 

      string connetionString = null; 
      SqlConnection cnn ; 
      connetionString = "Data Source=local.url;Initial Catalog=databasename;User ID=username;Password=password"; 

      cnn = new SqlConnection(connetionString); 

      string sql = "SELECT * FROM shiplabels"; 
      SqlDataAdapter a = new SqlDataAdapter(sql, cnn); 

      try 
      { 
       cnn.Open(); 
       a.Fill(t); 
       cnn.Close(); 
      } 
      catch (Exception ex) 
      { 
       Console.WriteLine ("Can not open connection ! "); 
      } 
     } 

我想連接到這個微軟數據庫並從中提取數據。我很難讓這個工作!當我使用這個代碼數據表t有0行,它應該回來幾百。我在這裏顯然缺少一些簡單的東西?

+0

該結果強烈暗示'shiplabels'表中確實存在零行。也許你在調試時忽略了一些東西? – David

+0

你拼錯的connectionString ...只是說。 – SqlZim

+0

爲什麼你不使用ORM? – adamshakhabov

回答

0
 DataTable dt = new DataTable(); 
     SqlDataAdapter sqlAdtp = new SqlDataAdapter(); 
     string connectionString = "Data Source=local.url;Initial Catalog=databasename;User ID=username;Password=password"; 
     string sql = "SELECT * FROM shiplabels"; 

     using (SqlConnection conn = new SqlConnection(connectionString)) 
     { 
      using (SqlCommand cmd = new SqlCommand(sql, conn)) 
      { 
       cmd.CommandType = CommandType.Text;     

       try 
       { 
        sqlAdtp.SelectCommand = cmd; 
        sqlAdtp.Fill(dt); 
       } 
       catch (Exception ex) 
       { 

       } 
      } 
     } 

首先,您不需要在使用SqlDataAdapter時打開連接。 另外,您忘記了CommandType。

+0

默認的CommandType是'文字' – Plutonix

+0

是的你是對的。忘了那個。 –

0

這應該適合你。

using System; 
using System.Windows.Forms; 
using System.Data; 
using System.Data.SqlClient; 

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

     private void button1_Click(object sender, EventArgs e) 
     { 
      string connetionString = null; 
      SqlConnection sqlCnn ; 
      SqlCommand sqlCmd ; 
      SqlDataAdapter adapter = new SqlDataAdapter(); 
      DataSet ds = new DataSet(); 
      int i = 0; 
      string sql = null; 

      connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password"; 
      sql = "Select * from product"; 

      sqlCnn = new SqlConnection(connetionString); 
      try 
      { 
       sqlCnn.Open(); 
       sqlCmd = new SqlCommand(sql, sqlCnn); 
       adapter.SelectCommand = sqlCmd; 
       adapter.Fill(ds); 
       for (i = 0; i <= ds.Tables[0].Rows.Count - 1; i++) 
       { 
        MessageBox.Show(ds.Tables[0].Rows[i].ItemArray[0] + " -- " + ds.Tables[0].Rows[i].ItemArray[1]); 
       } 
       adapter.Dispose(); 
       sqlCmd.Dispose(); 
       sqlCnn.Close(); 
      } 
      catch (Exception ex) 
      { 
       MessageBox.Show("Can not open connection ! "); 
      } 
     } 
    } 
}