c#的update语句怎么写?我是在Datagridview里更改数据,要更新到sql server里。

2025年03月23日 09:23
有3个网友回答
网友(1):

把我的代码贴给你看一下,懒得写,我把他写在类文件里:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;
using System.Windows.Forms;
using System.Reflection;
namespace CreazyDataWin32    
class linkdata
{
    public DataSet ds = null;
    public SqlDataAdapter sda = null;
    public static SqlConnection conn = null;
    public void OpenLink()  //打开链接
    {
       conn = new SqlConnection();
       conn.ConnectionString = "Server=192.168.1.2;UID=sa;PWD=111;DataBase=DB222";
       try
       {
          conn.Open();
       }
       catch
       {
          MessageBox.Show("连接数据库失败!");
       }
     }
     public void link(String sql) //链接数据库
     {
        if (conn != null)
        {
            ds = new DataSet();
            sda = new SqlDataAdapter();
            sda.SelectCommand = new SqlCommand(sql, conn);
            SqlCommandBuilder builder = new SqlCommandBuilder(sda);
            sda.Fill(ds);
        }
      }
      public void saveTable()  //保存数据
      {
         if (ds != null)
         {
             sda.Update(ds.Tables[0]);
             MessageBox.Show("操作已成功!","保存数据",MessageBoxButtons.OK,MessageBoxIcon.Information);
         }
       }
       public void filldata(DataSet ds, BindingNavigator b, DataGridView d)   //给dataGridview和导航绑定数据
        {
            BindingSource bs = new BindingSource();
            bs.DataSource = ds.Tables[0];
            b.BindingSource = bs;
            d.DataSource = bs;
        }
}

 登陆时初始化窗体,加载frame过程中就打开链接:

bll.linkdata l=new bll.linkdata();
l.OpenLink();

 使用的时候在窗体中这么写:

bll.linkdata l=new bll.linkdata();  //全局变量
void ViewData()   //查询数据
{
   l.link("SQL 查询语句");
   l.filldata(l.ds,bindingNavigator1,dataGridView1);
}
void saveData()  //这样就保存了dataGridView修改的数据,还不变他的而编辑状态
{
   l.savaTable();
}

程序结束时就关闭链接,够详细吧

网友(2):

创建方法:

 dgGrid_CellEndEdit(object sender, DataGridViewCellEventArgs e)

 

string sql = string.Format("update A set a1='{0}' where id='{2}'", dgGrid.Rows[e.RowIndex].Cells["dgcolumn1"].Value, dgGrid.Rows[e.RowIndex].Cells["dgcolumn2"].Value);

网友(3):

update 表名 set 列名=‘’ where 列 =条件