動態SQL C#實現.

來源:互聯網
上載者:User

set ANSI_NULLS ON

set QUOTED_IDENTIFIER ON

go

 

ALTER proc [dbo].[gb] @table_name
varchar(8) AS

 

declare @sql Nvarchar(1000) 

set @sql='update ' + @table_name +' set
id='+'123456 '+' where id='+'123'

--set @sql='update ' + ' aa '+'set
id='+'123456 '+ ' where id='+'123'

exec sp_executesql @sql with recompile

 上面的是預存程序  使用動態SQL語句

 

 

private void Form1_Load(object sender,
EventArgs e)

        {

          
 SqlConnection conn = new
SqlConnection("server=localhost;database=example;uid=example;pwd=example");

          

          
 try

          
 {

          
     conn.Open();

          
     label1.Text="串連成功!";

          
 }

          
 catch (Exception ex)

          
 {

          
     throw (ex);

 

          
 }

          
 String sql="exec select_table";

          
 DataSet ds = new DataSet();

          
 SqlDataAdapter da = new SqlDataAdapter(sql, conn);

          
 da.Fill(ds);

          
 dataGridView1.DataSource = ds.Tables[0];

 

          

          
 textBox1.Text=(String) dataGridView1.CurrentCell.Value;

          
 int row = this.dataGridView1.CurrentCell.RowIndex ;

   

          
    

          
 for (int i = row; i < dataGridView1.RowCount - 1; i++)

          
 {

          
     conn.Close();

          
     row = 0;

          
     this.dataGridView1.CurrentCell = this.dataGridView1[0, i];

 

          
  

          
     listBox1.Items.Add(this.dataGridView1.CurrentCell.Value);

          
     String mysql1 = "exec gb ", mysql2;

          
     mysql2 = (String)this.dataGridView1.CurrentCell.Value;

          
     mysql1 += mysql2;

          
     MessageBox.Show(mysql1);

          
     SqlCommand cmd = new SqlCommand("gb",conn);

          
     cmd.CommandType = CommandType.StoredProcedure;

          
     SqlParameter sp = new SqlParameter("@table_name",
SqlDbType.VarChar, 8);

          
     sp.Value = mysql2;

          
     cmd.Parameters.Add(sp);

          
     conn.Open();

          
     cmd.ExecuteNonQuery();

          
                     

          
     mysql2 = "";

        

          
   }

          
 conn.Close();

 

        }

 

迴圈執行預存程序。  終於把它弄完了。哈哈。以後用C#開發資料庫算了。哈哈。。。。

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.