Home  >  Article  >  Database  >  C#中MYSQL数据库连接并显示

C#中MYSQL数据库连接并显示

WBOY
WBOYOriginal
2016-06-07 15:39:40985browse

我是采用MYSQL实现的,所以首先需要导入MySql.Data.dll和MySQLDriverCS.dll,避免有些函数不能用。 命名空间: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq

我是采用MYSQL实现的,所以首先需要导入MySql.Data.dll和MySQLDriverCS.dll,避免有些函数不能用。

命名空间:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
using MySQLDriverCS;


winform用的是dataGridView,需要分以下几个步骤:

(1)数据库数据

MySqlConnection conn = new MySqlConnection("server = "+IPAdr+";uid = root; pwd =111;database =ser;charset=gb2312;");
conn.Open();

string str = "insert into ped values(NULL,' " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " ',' " + dataInfo + " ' ) ";    //主要ID且要有‘’号
MySqlCommand comm = new MySqlCommand(str,conn);
comm.ExecuteNonQuery();

comm.Dispose();
conn.Close();


注意:创建数据库时,时间的格式是timestamp,且要设置刷新当前时间戳记时;ID为自动递增且为主键;

(2)数据库连接及显示:

MySqlConnection conn = new MySqlConnection("server = 127.0.0.1;uid = root; pwd =111;database =ser;charset=gb2312;");
 MySqlCommand comm;
 conn.Open();
string str = "select * from ped";
                      
 MySqlDataAdapter da = new MySqlDataAdapter();                        // 实例化sqldataadpter
 MySqlCommand cmd1 = new MySqlCommand(str, conn);         // sql语句
 da.SelectCommand = cmd1;                                                            // 设置为已实例化SqlDataAdapter的查询命令
 DataSet ds1 = new DataSet();                                                          // 实例化dataset
 da.Fill(ds1);                                                                                           // 把数据填充到dataset
 dataGridView1.DataSource = ds1.Tables[0].DefaultView;          // 将数据集绑定datagridview,完成显示




Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn