c与数据库连接的详细步骤

c与数据库连接的详细步骤,第1张

C#连接数据库有以下几个步骤:

1:使用配置的数据库连接串,创建数据库连接 Connection 对象

2:构建 *** 作的sql语句

3:定义command对象

4:打开数据连接

5:执行命令

举一个例子,删除 *** 作

public class StudentService

{

//从配置文件中读取数据库连接字符串

private readonly static string connString = ConfigurationManager.ConnectionStrings["accpConnectionString"].ToString()

private readonly static string dboOwner = ConfigurationManager.ConnectionStrings["DataBaseOwner"].ToString()

AdoNetModels.Student model = new Student()

#region 删除数据1

public int DeleteStudent(int stuID)

{

int result = 0

// 数据库连接 Connection 对象

SqlConnection connection = new SqlConnection(connString)

// 构建删除的sql语句

string sql = string.Format("Delete From Student Where stuID={0}", stuID)

// 定义command对象

SqlCommand command = new SqlCommand(sql, connection)

try

{

connection.Open()

result = command.ExecuteNonQuery() // 执行命令

}

catch (Exception ex)

{

Console.WriteLine(ex.Message)

}

finally

{

connection.Close()

}

return result

}

#endregion

C++连接SQL数据库第一步 系统配置

1.设置SQLSERVER服务器为SQL登录方式,并且系统安全性中的sa用户要设置登录功能为“启用”,还有必须要有密码。

2.需要在ODBC中进行数据源配置,数据源选\”SQL SERVER”,登录方式使用“使用输入用户登录ID和密码的SQL SERVER验证”,并填写登录名(sa)和密码,注意一点,密码不能为空,这就意味着你的sa用户必须得有密码。否则无法通过系统本身的安全策略。测试通过就完成了配置。

C++连接SQL数据库第二步 C++与SQL连接初始化

1.在你所建立的C++项目中的stdafx.h头文件中引入ADO

具体代码如下

#import “c:\Program Files\Common Files\System\ado\msado15.dll”

no_namespace rename(”EOF”, “adoEOF”) rename(”BOF”, “adoBOF”)

2.定义_ConnectionPtr变量后调用Connection对象的Open方法建立与服务器的连接。

数据类型_ConnectionPtr实际上是由类模板_com_ptr_t得到的一个具体的实例类。_ConnectionPtr类封装了Connection对象的Idispatch接口指针及其一些必要的 *** 作。可以通过这个指针 *** 纵Connection对象。

例如连接SQLServer数据库,代码如下:

//连接到MS SQL Server

//初始化指针

_ConnectionPtr pMyConnect = NULL

HRESULT hr = pMyConnect.CreateInstance(__uuidof(Connection))

if (FAILED(hr))

return

//初始化链接参数

_bstr_t strConnect = “Provider=SQLOLEDB

Server=hch

Database=mytest

uid=sapwd=sa”//Database指你系统中的数据库

//执行连接

try

{

// Open方法连接字串必须四BSTR或者_bstr_t类型

pMyConnect->Open(strConnect, “”, “”, NULL)

}

catch(_com_error &e)

{

MessageBox(e.Description(), “警告”, MB_OK|MB_ICONINFORMATION)

}//发生链接错误

C++连接SQL数据库第三步 简单的数据连接

//定义_RecordsetPtr变量,调用它Recordset对象的Open,即可打开一个数据集

//初始化过程 以下是个实例

_RecordsetPtr pRecordset

if (FAILED(pRecordset.CreateInstance(__uuidof(Recordset))))

{

return

}

//执行 *** 作

try

{

pRecordset->Open(_variant_t(”userinfo”),

_variant_t((IDispatch*)pMyConnect),

adOpenKeyset, adLockOptimistic, adCmdTable)

}

catch (_com_error &e)

{

MessageBox(”无法打开userinfo表\”, “系统提示”,

MB_OK|MB_ICONINFORMATION)

}

C++连接SQL数据库第四步 执行SQL语句

这里是关键,我认为只要你懂点SQL语句那么一切都会方便许多比用上面的方法简单,更有效率点。

首先

m_pConnection.CreateInstance(_uuidof(Connection))

//初始化Connection指针

m_pRecordset.CreateInstance(__uuidof(Recordset))

//初始化Recordset指针

CString strSql=”select * from tb_goods”//具体执行的SQL语句

m_pRecordset=m_pConnection->Execute(_bstr_t(strSql),

NULL, adCmdText)//将查询数据导入m_pRecordset数据容器

至此 你的SQL语句已经执行完成了m_pRecordset内的数据就是你执行的结果。

取得记录:

while(!m_pRecordset->adoEOF)//遍历并读取name列的记录并输出

{

CString temp = (TCHAR *)(_bstr_t)m_pRecordset->GetFields()->GetItem

(”name”)->Value

AfxMessageBox(temp)

pRecordset->MoveNext()

}

插入记录

//记得初始化指针再执行以下 *** 作

CString strsql

strsql.Format(”insert into tb_goods(no,name, price)

values(’%d’,'%s’, %d)”,m_intNo,m_strName,m_intPrice)

m_pRecordset=m_pConnection->

Execute(_bstr_t(strsql),NULL,adCmdText)

修改记录

CString strsql

strsql.Format(”update tb_goods set name=’%s’ ,

price=%d where no=%d “,m_strName,m_intPrice,m_intNo)

m_pRecordset=m_pConnection->Execute(_bstr_t(strsql),NULL,adCmdText)

删除记录

CString strsql

strsql.Format(”delete from tb_goodswhere no= ‘%d’ “,m_intNo)

m_pRecordset=m_pConnection->Execute(_bstr_t(strsql),NULL,adCmdText)

//vc工具中添加E:\WAMP\BIN\MYSQL\MYSQL5.5.8\LIB 路径

//在工程设置-》链接》库模块中添加 libmysql.lib

#include <stdio.h>

#include <time.h>

#include <string.h>

#include <winsock.h>

#include "E:\wamp\bin\mysql\mysql5.5.8\include\mysql.h"

void main(){

MYSQL *conn

MYSQL_RES *res

MYSQL_ROW row

char *server ="localhost"

char *user ="root"

char *password=""

char *database="test"

char sql[1024]="select * from chinaren"

conn=mysql_init(NULL)

if(!mysql_real_connect(conn,server,user,password,database,0,NULL,0)){

fprintf(stderr,"%s\n",mysql_error(conn))

exit(1)

}

if(mysql_query(conn,sql)){

fprintf(stderr,"%s\n",mysql_error(conn))

exit(1)

}

res=mysql_use_result(conn)

while((row = mysql_fetch_row(res))!=NULL){

printf("%s\n",row[2])

}

mysql_free_result(res)

mysql_close(conn)

}

===============================

#if defined(_WIN32) || defined(_WIN64) //为了支持windows平台上的编译

#include <windows.h>

#endif

#include <stdio.h>

#include <stdlib.h>

#include "mysql.h"

//定义数据库 *** 作的宏,也可以不定义留着后面直接写进代码

#define SELECT_QUERY "show tables"

int main(int argc, char **argv) //char **argv 相当于 char *argv[]

{

MYSQL mysql,*handle //定义数据库连接的句柄,它被用于几乎所有的MySQL函数

MYSQL_RES *result //查询结果集,结构类型

MYSQL_FIELD *field//包含字段信息的结构

MYSQL_ROW row //存放一行查询结果的字符串数组

char querysql[160] //存放查询sql语句字符串

//初始化

mysql_init(&mysql)

//连接数据库

if (!(handle = mysql_real_connect(&mysql,"localhost","user","pwd","dbname",0,NULL,0))) {

fprintf(stderr,"Couldn't connect to engine!\n%s\n\n",mysql_error(&mysql))

}

sprintf(querysql,SELECT_QUERY,atoi(argv[1]))

//查询数据库

if(mysql_query(handle,querysql)) {

fprintf(stderr,"Query failed (%s)\n",mysql_error(handle))

}

//存储结果集

if (!(result=mysql_store_result(handle))) {

fprintf(stderr,"Couldn't get result from %s\n", mysql_error(handle))

}

printf("number of fields returned: %d\n",mysql_num_fields(result))

//读取结果集的内容

while (row = mysql_fetch_row(result)) {

printf("table: %s\n",(((row[0]==NULL)&&(!strlen(row[0]))) ? "NULL" : row[0]) )

}

//释放结果集

mysql_free_result(result)

//关闭数据库连接

mysql_close(handle)

system("PAUSE")

//为了兼容大部分的编译器加入此行

return 0

}


欢迎分享,转载请注明来源:内存溢出

原文地址: http://www.outofmemory.cn/sjk/6809600.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-03-28
下一篇 2023-03-28

发表评论

登录后才能评论

评论列表(0条)

保存