1、安裝
sudo apt-get install mysql-server
mysql-client 安裝
過程中需要配置root的密碼。
通過service mysql status 可以查看已經(jīng)安裝好的mysql的運行情況。
2、修改默認的存儲文件和其他相關(guān)配置
配置文件:/etc/mysql/my.cnf
內(nèi)容:
!includedir /etc/mysql/conf.d/
!includedir /etc/mysql/mysql.conf.d/
從上面看來,所以實際需要修改/etc/mysql/mysql.conf.d/mysqld.cnf文件,需要注意的是可不動sock文件,否則很容易報錯。
A、添加client,不然sock報錯
[client]
default-character-set=utf8
socket = /var/run/mysqld/mysqld.sock
B、配置utf8編碼
[mysqld]
character-set-server=utf8
collation-server=utf8_general_ci
C、修改datadir = (your data path)
原有的東西拷貝過去:cp -arf /var/lib/mysql (your data path)/mysql
授權(quán):sudo chown -R mysql.mysql mysql
D、注釋掉配置文件里面的bind-address = 127.0.0.1,開啟遠程訪問
E、需要selinux設(shè)置為disable和apparmor相關(guān)路徑修改,二者語mysql有限制
selinux 設(shè)置為disable,可以通過getenforce查看,通過setenforce 0 直接設(shè)置。若命令不存在安裝一下包
apparmor,在 /etc/apparmor.d/usr.sbin.mysqld 這個文件中,規(guī)定了mysql使用的數(shù)據(jù)文件路徑權(quán)限
/var/lib/mysql/ r,/var/lib/mysql/** rwk,
其中/var/lib/mysql/就是之前mysql安裝的數(shù)據(jù)文件默認路徑,apparmor控制這里mysqld可以使用的目錄的權(quán)限 照上面那兩條,注釋掉上面的,增加下面這兩條就可以了
(your data path)/mysql/ r,
(your data path)/mysql/** rwk,
重啟: sudo service apparmor restart
3、sudo /etc/init.d/mysql restart 啟動mysql
通過sudo service mysql start/stop來啟動和停止mysql,確定沒問題
通過/var/log/mysql/error.log來定位錯誤
如果遇到問題了實在解決不了可以sudo apt-get autoremove mysql* --purge,刪除了在重新裝
4、grant all on 數(shù)據(jù)庫名.* to '用戶名' identified by '密碼';
給用戶授予某數(shù)據(jù)庫的訪問權(quán)限,其中db事先建立好。注意text字段有strict mode模式,這種模式下不能設(shè)置默認值為‘’
5、python連接db
從git下載包:https://github.com/PyMySQL/PyMySQL
下載后解壓,然后通過python setup.py install --user 安裝到當前用戶目錄下。
# -*- coding:utf-8 -*-import pymysql#創(chuàng)建連接con = pymysql.connect(host='***', port=3306, user='***', passwd='***', db='***', charset='utf8')# 創(chuàng)建游標cursor = con.cursor()
# 執(zhí)行SQL,并返回收影響行數(shù)effect_row = cursor.execute("select * from table")
#獲取首行的結(jié)果row_1 = cursor.fetchone()
# 獲取剩余結(jié)果前n行數(shù)據(jù)row_2 = cursor.fetchmany(3)# 獲取剩余結(jié)果所有數(shù)據(jù)row_3 = cursor.fetchall()
con.commit()cursor.close()
con.close()
6、c++連接db
#include <iostream>
#include <mysql/mysql.h>
#include <stdio.h>
#include <string.h>
using namespace std;
int main(int argc, char* argv[])
{
//準備mysql的訪問結(jié)構(gòu)
MYSQL mysql;
mysql_init( &mysql );
mysql_real_connect(
&mysql,
"***", //要訪問數(shù)據(jù)庫的IP地址
"***", //用戶名
"***", //密碼
"***", //要訪問的數(shù)據(jù)庫
3306, //該數(shù)據(jù)庫的端口
NULL, //一般為NULL
0 //一般為0
);
//插入
string sql = "insert into table(字段1,字段二) values ('***','***')";
//執(zhí)行sql語句
mysql_query(&mysql,"SET NAMES utf8"); //防止中文亂碼
mysql_query( &mysql, sql.c_str() );
//關(guān)閉數(shù)據(jù)庫連接
mysql_close( &mysql );
return 0;
}