C++和C#访问MySQL的简单代码示例
贴一份示例代码。非常适合于初学者使用。1) C#访问mysql
using System;
using System.Collections.Generic;
using System.Text;
using MySql.Data.MySqlClient;
using System.Data;
using System.Data.Common;
namespace SybaseUtilTest
{
class Program
{
// http://bugs.mysql.com/47422, 有兴趣的朋友,可以看看这个bug是怎么回事
static void testDataAdapter()
{
try
{
MySqlClientFactory factory = MySqlClientFactory.Instance;
DbConnection conn = factory.CreateConnection();
conn.ConnectionString = string.Format("server={0};user id={1}; password={2}; database={3}; port={4}; pooling=false",
"localhost", "root", "passwd", "test", 3306);
conn.Open();
DbDataAdapter da = factory.CreateDataAdapter();
da.SelectCommand = conn.CreateCommand();
da.SelectCommand.CommandText = "select * from t12345";
da.DeleteCommand = conn.CreateCommand();
da.DeleteCommand.CommandText = "delete from t12345 where id = @id";
DbParameter param = factory.CreateParameter();
param.ParameterName = "@id";
param.DbType = DbType.Int32;
param.SourceColumn = "id";
param.SourceVersion = DataRowVersion.Current;
da.DeleteCommand.Parameters.Add(param);
da.DeleteCommand.UpdatedRowSource = UpdateRowSource.None;
DataTable dt = new DataTable("t12345");
da.Fill(dt);
int index = 0;
foreach ( DataRow o in dt.Rows )
{
if (o["id"].Equals(4))
{
Console.WriteLine(String.Format("index={0}, to delete id = 4, col2 = {1}" , index, o["col2"]));
break;
}
index++;
}
dt.Rows[index].Delete();
da.Update(dt);
dt.AcceptChanges();
da.Dispose();
conn.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Source + " "
+ ex.Message + " "
+ ex.StackTrace);
}
}
static void Main(string[] args)
{
testDataAdapter();
}
}
}
2) C++访问 (直接调用C-API)
#include <iostream>
#include <windows.h>
#include <mysql.h>
#include <string>
static const char host[32] = "localhost";
static const char user[32] = "test";
static const char passwd[32] = "passwd";
static const char db[32] = "test";
/**
mysql> select * from t;
+----+
| id |
+----+
| 1 |
+----+
1 row in set (0.00 sec)
mysql> delimiter //
mysql> create procedure get_t(in t1 int)
-> begin
-> select id from t where id=t1;
-> end
-> //
Query OK, 0 rows affected (0.05 sec)
mysql> call get_t(1);
-> //
+----+
| id |
+----+
| 1 |
+----+
1 row in set (0.00 sec)
Query OK, 0 rows affected (0.00 sec)
*/
void test_more_results(MYSQL* h)
{
char str[512] = "insert into test_num values(101);insert into test_num values(122);commit;";
int r = mysql_real_query(h, str, strlen(str));
if (r)
{
const char * error = mysql_error(h);
std::cout<<"**
补充:软件开发 , C++ ,
- 更多SQLServer疑问解答:
- 配置MSSQL复制指定快照文件夹提示:不是有效的路径或文件名
- 详细解读varchar和Nvarchar区别
- SQL SERVER 2005 同步复制技术
- 进程未能大容量复制到表 解决方法
- MSSql实例教程:MSSql数据库同步
- SQLServer2000同步复制技术实现(分发和订阅)
- sqlserver
- SQLSERVER
- 测试 sqlserver 最大用户数连接
- 写出一条Sql语句:取出表A中第31到第40记录(SQLServer,以自动增长的ID作为主键,注意:ID可能不是连续的
- sqlserver2008的安装问题。
- 为什么安装的SQL server 2008我的没有MSSQLSERVER协议啊?
- 怎样把exel表里的数据复制到sqlserver表里
- sqlserver数据库主键和外键问题
- sqlserver 中的左表连接查询和右表连接查询有啥不同?有什么用?