4.MySQL连接并选择数据库(SQL C)
在連接了MySQL數據庫之后,可以通過SQL命令或者C、PHP、JAVA等程序來指定需要操作的數據庫。這里主要介紹SQL命令和相應的C程序。
首先創建用戶rick(賦予所有權限)
mysql> grant ALL ON *.* TO rick@localhost IDENTIFIED BY 'rick123'
然后給rick用戶創建兩個數據庫
mysql> \q # mysqladmin -u rick -p create foo;# mysqladmin -u rick -p create foo2;
?
1.SQLl命令
實例,選擇數據庫foo
root@deamon-H55M-S2:/# mysql -u rick -p Enter password: Welcome to the MySQL monitor. Commands end with ; or \g. Your MySQL connection id is 15 Server version: 5.7.16-0ubuntu0.16.04.1 (Ubuntu)Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved.Oracle is a registered trademark of Oracle Corporation and/or its affiliates. Other names may be trademarks of their respective owners.Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.mysql> use foo; Reading table information for completion of table and column names You can turn off this feature to get a quicker startup with -ADatabase changed
2.C程序
相關函數:MYSQL *mysql_init(MYSQL *mysql) 該函數初始化一個適合用于mysql_real_connect的連接句柄結構
MYSQL *mysql_real_connect(MYSQL *mysql,
const char *host,
const char *user,
const char *passwd,
const char *db,
unsigned int port,
const char *unix_socket,
unsigned long client_flag);//連接數據庫
MYSQL *mysql_close(MYSQL *mysql) //關閉連接,通常在程序結束退出時,需要調用該函數進行關閉。
如果mysql是一個空指針,mysql_init函數會分配、初始化以及返回一個新的句柄結構,否則mysql會被重新初始化,并返回該結構的地址。mysql_init 分配的新結構會在調用mysql_close()時被釋放。
例程:
#include<stdio.h> #include<stdlib.h> #include<mysql/mysql.h> int main() {MYSQL my_connect;mysql_init(&my_connect);
//以rick的身份連接數據庫,并選擇使用數據庫foo;if(mysql_real_connect(&my_connect,"localhost","rick","rick123","foo",0,NULL,0))printf("Connect success\n");elseprintf("Connect failed\n");//選擇數據庫foo2;if(!mysql_select_db(&my_connect,"foo2"))printf("Select Database success\n");elseprintf("Select Database failed\n");}
編譯程序:
gcc -I/usr/include/mysql select_db.c -L/usr/lib/mysql -lmysqlclient -o select_db
最后執行程序
./select_db Connect success Select Database success
注意:如果編譯的時候顯示mysql.h找不到,那么需要安裝libmysqlclient-dev
對Ubuntu,Debian等 apt-get install libmysqlclient-dev 對Centos等 apt-get install libmysqlclient-dev
安裝完成后頭文件在/usr/include/mysql
?
轉載于:https://www.cnblogs.com/jiandahao/p/6119154.html
總結
以上是生活随笔為你收集整理的4.MySQL连接并选择数据库(SQL C)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 红双喜罐装4891132010328多少
- 下一篇: 以八开头的成语有哪些啊?