基础 ADO.NET 访问MYSQL 与 MSSQL 数据库例子

虽然实际开发时都是用 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(); } }
复制代码

上面给的是一个 MYSQL 的例子。

这里我要说说 SQL SERVER (MSSQL) 的区别。

1. Class不同, 上面的全部 "MySql" 改成 Sql 就可以了

2. CommandType 的namespace 不同, MSSQL 是在 System.Data

3. cosmmand 的 para 符号不同

  "select * from task_record where id=?para0" <- MySql 用的是问号 "?"

    "select * from task_record where id=@para0" <- SQL SERVER 用的是 "@"

4. command.Transaction = transaction <-- MSSQL 必须加多一句,每个command 必须要填写 transaction , 如果你有开的话 

5. 

   command.CommandText = "insert into product (code,name) output inserted.id values ('mk400','puma')";
            int result = (int)command.ExecuteScalar(); 

如果要获得last inserted id , 是通过 command output. (我不清楚这算不算SQL规范语句)

 

posted @   兴杰  阅读(400)  评论(0编辑  收藏  举报
编辑推荐:
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
阅读排行:
· 百万级群聊的设计实践
· 全网最简单!3分钟用满血DeepSeek R1开发一款AI智能客服,零代码轻松接入微信、公众号、小程
· .NET 10 首个预览版发布,跨平台开发与性能全面提升
· 《HelloGitHub》第 107 期
· 从文本到图像:SSE 如何助力 AI 内容实时呈现?(Typescript篇)
点击右上角即可分享
微信分享提示