Mysql 插入中文及中文查詢 (修改+調試)

來源:互聯網
上載者:User

//我修改之,能正常運行,測試環境為mysql5.0,xp
//關鍵是設定對字元集,設定gbk,gb2312測試通過,utf8測試未通過
//在運行程式前先建立資料庫jj,注意下面幾個參數(修改為你自己的) 複製代碼 代碼如下:// char *host = "localhost";
// char *user = "root";
// char *pass = "674800";
// char *db = "jj";
#include <windows.h>
#include <iostream>
#include <mysql.h>
#include <stdio.h>
#include <string.h>
using namespace std;
#pragma comment(lib,"libmysql.lib")
int connDB();
int create_table();
int insert_table();
int select_table();
int disconnDB();
MYSQL *mysql;
MYSQL_RES *res;
MYSQL_FIELD * fd;
MYSQL_ROW row;
char szSqlText[500]="";
int i;
int main()
{
connDB();
// create_table();
insert_table();
select_table();
disconnDB();
return 0;
}
///////////////子函數
int connDB()//串連資料庫
{
char *host = "localhost";
char *user = "root";
char *pass = "674800";
char *db = "jj";
mysql = mysql_init((MYSQL*) 0);
mysql_real_connect( mysql, host, user, pass, db,3306, NULL, 0 ) ; //連結到伺服器
mysql_set_character_set(mysql,"gb2312"); //設定字元集
cout<<"conn OK!"<<endl;
return 0;
}
//關閉資料庫
int disconnDB()
{
mysql_close( mysql ) ;
cout<<"disconn OK!"<<endl;
return 0 ;
}
//建立表
int create_table()
{
mysql_set_character_set(mysql,"gb2312");
sprintf(szSqlText, \
"create table mytable \
(s0 varchar(100), \
s1 char(6),\
s2 varchar(4),\
s3 varchar(3),s4 int)\
ENGINE=InnoDB \
DEFAULT CHARSET=gb2312");
if(mysql_query( mysql, szSqlText))
cout<<"occurred an error:"<<mysql_error(mysql)<<endl;
return 0;
}
int insert_table()
{
mysql_set_character_set(mysql,"gb2312");
sprintf(szSqlText,
"insert into mytable\
values('2000-3-10 21:01:30',\
'Test',\
'清風寒劍',\
'歲月情',\
2500)");
if( mysql_query( mysql, szSqlText) )
cout<<"occurred an error:"<<mysql_error(mysql)<<endl;
return 0;
}
int select_table()
{
mysql_set_character_set(mysql,"gb2312");
sprintf(szSqlText, "select * from mytable ");
if (mysql_query( mysql, szSqlText))
{
cout<<"occurred an error:"<<mysql_error(mysql)<<endl;
mysql_close( mysql ) ;
return FALSE ;
}
res = mysql_store_result( mysql) ;
i = (int) mysql_num_rows( res ) ;
cout<<"Query: "<<szSqlText<<"\n"<<i<<" records found:"<<endl;
for ( i = 0 ; fd = mysql_fetch_field( res ) ; i++ )
cout<<fd->name<<"\t";
cout<<endl;
while(row = mysql_fetch_row( res ))
cout<<row[0]<<"\t"<<row[1]<<"\t"<<row[2]<<"\t"<<row[3]<<"\t"<<row[4]<<endl;
mysql_free_result( res ) ;
cout<<"select OK!"<<endl;
return 0;
}

我機器上的運行結果:

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.