C#从数据库mysql读取数据
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using MySql.Data.MySqlClient; namespace 电子商务 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { } private void button1_Click(object sender, EventArgs e) { string str = "Host=localhost;User ID=root;Password=;Port = 3306;DataBase=animals;Charset=utf8;"; MySqlConnection conn = new MySqlConnection(str); conn.Open();// ////拿到数据库并打开连接 //string sql = "select *from student"; //MySqlCommand cmd = new MySqlCommand(sql, conn); //MySqlDataAdapter mda = new MySqlDataAdapter(cmd); //DataSet ds = new DataSet(); //mda.Fill(ds); //dataGridView1.DataSource = ds.Tables[0]; ////MySqlDataReader dr = cmd.ExecuteReader(); //conn.Close(); /*1.访问数据库的五大步骤 2.拿到要发送的sql语句 3.执行 sql 语句 4.拿到执行后的聚过 5.关闭连接 切记关闭连接 */ ////1 拿到数据库的连接 并打开连接 //string url = "User ID=root;Password=;Host=localhost;Port=3306;Database=xx;charset=xx;"; //MySqlConnection con = new MySqlConnection(url); //con.Open(); ////2.要拿到要发送的sql语句 //string sql = "select id from student where name='kobe'"; //MySqlCommand com = new MySqlCommand(sql, con); //// 3 执行 sql 语句 //MySqlDataReader reader = com.ExecuteReader(); //reader.Read();// Read() 每次调用 都会从结果集中返回一行数据 //reader.GetInt32(0); /*1.访问数据库的五大步骤 2.拿到要发送的sql语句 3.执行 sql 语句 4.拿到执行后的聚过 5.关闭连接 切记关闭连接 */ //1 拿到数据库的连接 并打开连接 string url = "User ID=root;Password=;Host=localhost;Port=3306;Database=students;"; MySqlConnection con = new MySqlConnection(url); con.Open(); //2.要拿到要发送的sql语句 string sql = "select *from student where name='kobe'"; MySqlCommand com = new MySqlCommand(sql, con); // 3 执行 sql 语句 MySqlDataReader reader = com.ExecuteReader(); reader.Read();// Read() 每次调用 都会从结果集中返回一行数据 //reader.GetInt32(0); Console.WriteLine(reader.GetInt32(0)); con.Close(); ////对数据库进行 增 删 改 查 ////1 拿到数据库的连接 并打开连接 //string url = "User ID=root;Password=root;Host=localhost;Port=3306;Database=students;"; //MySqlConnection con = new MySqlConnection(url); //con.Open(); //string sql = "insert into student values(11,'hahahaha','man',6)";//添加信息 //MySqlCommand cmd = new MySqlCommand(sql, con); //int result = cmd.ExecuteNonQuery(); //Console.WriteLine("数据库打开结果:"+result); //con.Close(); //FindStudent("kobe"); } public static bool FindStudent(string name) { bool b = false; string url = "User ID=root;Password=root;Host=localhost;Port=3306;Database=students;"; MySqlConnection con = new MySqlConnection(url); con.Open(); string sql = "select *from studnet where name='{0}' "; sql = string.Format(sql, name); // Console.WriteLine(sql); MySqlCommand cmd = new MySqlCommand(sql, con); MySqlDataReader reader = cmd.ExecuteReader(); b = reader.Read(); return b; } } }