我将MYSQL Server用作项目后端。我有一个DataGridView,该数据库填充了数据库中的数据。当我在DataGridView单元格中进行更改并单击saveButton时,数据需要在DataGridView和数据库表中进行更改。
这是我的编码:
using MySql.Data.MySqlClient;
using System;
using System.Data;
using System.IO;
using System.Windows.Forms;
namespace datagridview
{
public partial class Form1 : Form
{
DataTable datatab;
MySqlDataAdapter mydtadp;
MySqlCommandBuilder cmbl;
String MyConnection = "SERVER=*****;" +
"DATABASE=****;" +
"UID=root;" +
"PASSWORD=pws";
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
MySqlConnection MyConn = new MySqlConnection(MyConnection);
MyConn.Open();
MySqlCommand comand = new MySqlCommand("select * from aster_scripts;", MyConn);
datatab = new DataTable();
mydtadp = new MySqlDataAdapter(comand);
mydtadp.Fill(datatab);
dataGridView1.DataSource = datatab;
MyConn.Close();
}
private void BtnSave_Click(object sender, EventArgs e)
{
DataSet ds = new DataSet();
cmbl = new MySqlCommandBuilder(mydtadp);
mydtadp.Update(datatab);
MessageBox.Show("SAVED");
}
}
}
我在mydtadp.Update(datatab)行中遇到了这样的错误(附加信息:针对不返回任何键列信息的SelectCommand,不支持为UpdateCommand生成动态SQL。);如何才能做到这一点?
请注意模块级变量。并在需要时参考此MSDN文章。
create table aster_scripts
( id int auto_increment primary key,
i int not null,
sThing varchar(30) not null
);
insert aster_scripts (i,sThing) values (8,'frog'),(11,'cat');
using System;
using System.Data;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
using System.IO;
namespace WindowsFormsApplication1
{
public partial class Form2 : Form
{
private MySqlDataAdapter mydtadp = new MySqlDataAdapter();
private BindingSource bindingSource1 = new BindingSource();
MySqlCommandBuilder cmbl;
String MyConnection = "SERVER=hostname;" +
"DATABASE=dbname;" +
"UID=dbuser;" +
"PASSWORD=fffff";
public Form2()
{
InitializeComponent();
}
private void Form2_Load(object sender, EventArgs e)
{
MySqlConnection MyConn = new MySqlConnection(MyConnection);
MyConn.Open();
mydtadp.SelectCommand=new MySqlCommand("select * from aster_scripts", MyConn);
cmbl = new MySqlCommandBuilder(mydtadp);
DataTable table = new DataTable();
mydtadp.Fill(table);
bindingSource1.DataSource = table;
dataGridView1.DataSource = bindingSource1;
}
private void BtnSave_Click(object sender, EventArgs e)
{
mydtadp.Update((DataTable)bindingSource1.DataSource);
MessageBox.Show("SAVED");
}
}
}
mysql> select * from aster_scripts;
+----+----------+--------+
| id | i | sThing |
+----+----------+--------+
| 1 | 8 | frog |
| 2 | 11333322 | cat |
+----+----------+--------+
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句