C#中MySQL函数用DATASET 和 MySqlDataAdapter 操作数据库

1.C#中调用MYSQL数据库时,我用的是MySQLDriverCS这个方法.

一般的查询可以方便执

            String connStr, commStr;
            DataSet ds;       //数据集
            BindingSource bs;  //数据绑定源,注意是全局的变量
            MySQLConnection myconn;
            MySQLDataAdapter myadp;//数据适配器            

            connStr = "Data Source=myshiyandb;Password=110810;User ID=root;Location=localhost;Port=3306;Extended Properties=";//数据库连接字符串
            //myconn = new MySQLConnection(new MySQLConnectionString("localhost", "myshiyandb", "root", "110810").AsString);
            myconn = new MySQLConnection(connStr);
            
            try
	    {
	        myconn.Open();//打开数据库
            }
	    catch(Exception e)
            {
	        MessageBox.Show(e.Message);
	     }
             //
	    ds = new DataSet();
            commStr = "select * from table1;";
            
            myadp = new MySQLDataAdapter(commStr , myconn); //适配器 
            myadp.Fill(ds,"table"); //将查询到数据填充到数据集
	    bs = new BindingSource();
	    bs.DataSource = ds.Tables["table"];
	    dataGridView1.DataSource = bs; //绑定DataGridView到DataSet
	    //shut
            try
            {
	        myconn.Close();
             }
	     catch(Exception e)
            {
	        MessageBox.Show(e.Message);
	    }

2.但是在通过这种方法,改一下其中的sql语句,虽然程序执行了,但是记录添加不到数据库中;解决办法

            connStr = "Data Source=myshiyandb;Password=110810;User ID=root;Location=localhost;Port=3306;Extended Properties=";//数据库连接字符串
            //myconn = new MySQLConnection(new MySQLConnectionString("localhost", "myshiyandb", "root", "110810").AsString);
            myconn = new MySQLConnection(connStr);

            try
            {
                myconn.Open();//打开数据库
            }
            catch (Exception e2)
            {
                MessageBox.Show(e2.Message);
            }

            string strInsert = null;
            strInsert = " insert into " + "table1" + " values "
                        + " ( "
                        + "'" + tbxLuruName.Text + "'" + ", "
                        + tbxLuruAge.Text 
                        + " ) ";
            //---
            commStr = strInsert;
            MySQLCommand cmd = new MySQLCommand(commStr, myconn);
            cmd.ExecuteNonQuery(); 
            //myadp = new MySQLDataAdapter(commStr, myconn); //适配器 
            
            try
            {
                myconn.Close();
            }
            catch (Exception e3)
            {
                MessageBox.Show(e3.Message);
            }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值