標籤:open text set bool void insert base and grid
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; } }}
C#從資料庫mysql讀取資料