基础 ADO.NET 访问MYSQL数据库例子
虽然实际开发时都是用 Entity 了,但是基础还是要掌握和复习的 ^^
//set connection string, server,database,username,password MySqlConnection con = new MySqlConnection("SERVER=localhost;DATABASE=Gridview;UID=keatkeat;PASSWORD=001001"); MySqlTransaction transaction = null;
MySqlDataReader reader = null; try { MySqlCommand command = new MySqlCommand(); command.Connection = con; command.CommandType = CommandType.Text; con.Open(); transaction = con.BeginTransaction(); command.CommandText = "select * from task_record where id=?para0"; //add and remove parameters command.Parameters.Clear(); command.Parameters.AddWithValue("?para0", 1); //for protect sql inject attack //for insert update //int result = command.ExecuteNonQuery(); //long lastInsertId = command.LastInsertedId; transaction.Commit(); //for select then use Adapter MySqlDataAdapter adapter = new MySqlDataAdapter(command); DataTable table = new DataTable(); adapter.Fill(table); //装入table之后就可以调用了 for (int i = 0, l = table.Rows.Count; i < l; i++) { for (int a = 0, b = table.Columns.Count; a < b; a++) { string columnName = table.Columns[a].ColumnName; } string someData = table.Rows[i]["columnName"].ToString(); } //select then use reader reader = command.ExecuteReader(); int colummCount = reader.FieldCount; int rowIndex = 0; while (reader.Read()) //reader 内的数据只能被read 一次哦 { for (int i = 0; i < colummCount; i++) { string columnName = reader.GetName(i); object value = reader[i]; } rowIndex++; } reader.Close(); } catch (Exception ex) { if (transaction != null) transaction.Rollback(); string x = ex.Message; } finally { if (con.State == System.Data.ConnectionState.Open) { con.Close(); } }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。