Mysql資料庫中的資訊匯入到redis中

2021-09-27 11:14:03 字數 2110 閱讀 1733

最近學習了redis,想要加入到之前的專案中,之前的用的資料庫是mysql。第一步需要做的就是將mysql資料庫中現有的資料匯入到redis中,在網上查閱資料後,使用的方法是利用指令碼將mysql中的戶數轉換為redis-cli可以識別的格式,直接批量插入。下面是具體的過程,碰到的問題以及解決方法。

一、具體過程

1. 表的結構:

2. 編寫指令碼:

根據資料表的結構,讀取資料表中的資料,然後以redis可以識別的格式將資料寫入到redis中。

select concat(  

"*12\r\n",  

'$', length(redis_cmd), '\r\n',  

redis_cmd, '\r\n',  

'$', length(redis_key), '\r\n',  

redis_key, '\r\n',

'$', length(hkey1), '\r\n',  hkey1, '\r\n','$', length(hval1), '\r\n',  hval1, '\r\n'

'$', length(hkey2), '\r\n',  hkey2, '\r\n','$', length(hval2), '\r\n',  hval2, '\r\n'  

'$', length(hkey3), '\r\n',  hkey3, '\r\n','$', length(hval3), '\r\n',  hval3, '\r'     

)  from (  

select  

'hmset' as redis_cmd,  

concat('userid:' ,userid) as redis_key,  

'password' as hkey1, password as hval1,

'name' as hkey2, name as hval2,

'phone_num' as hkey3, phone_num as hval3,  

from users  

) as t 

3.使用以下指令進行匯入:

mysql -uroot -ppassword -h 127.0.0.1 database --skip-column-names --raw < /myredis/user.sql | /usr/local/bin/redis-cli -p 6379 --pipe

4.結果報錯了,如下:

在網上查閱資料後發現,原來是因為:redis中的空資料是以字串空串的形式儲存的,而mysql中則為null,所以在匯入到redis的時候出錯了。

select concat(  

"*12\r\n",  

'$', length(redis_cmd), '\r\n',  

redis_cmd, '\r\n',  

'$', length(redis_key), '\r\n',  

redis_key, '\r\n',

'$', length(hkey1), '\r\n',  hkey1, '\r\n','$', length(hval1), '\r\n',  hval1, '\r\n'

'$', length(hkey2), '\r\n',  hkey2, '\r\n','$', length(hval2), '\r\n',  hval2, '\r\n'  

'$', length(hkey3), '\r\n',  hkey3, '\r\n','$', length(hval3), '\r\n',  hval3, '\r'     

)  from (  

select  

'hmset' as redis_cmd,  

concat('userid:' ,userid) as redis_key,  

'password' as hkey1, password as hval1,

'name' as hkey2, name as hval2,

'phone_num' as hkey3, if(phone_num is not null, phone_num, '') as hval3,  

from users  

) as t 

5. 正確結果:

成功將mysql資料庫中user表中的107條記錄匯入到redis中

Excel的資料匯入到資料庫中

匯入資料的時候就是怎麼鏈結excel表?鏈結的時候最好有字尾名。dataset mydataset new dataset 建立乙個資料鏈結 string strcon provider microsoft.jet.oledb.4.0 data source filename extended pr...

PHPExcel匯入到資料庫

使用phpexcel 讀取excel 資料到資料庫 建立乙個讀取excel資料,可用於入庫 function readexcel file return datas excel 資料 批量匯入資料庫 param string table 表名 param array excel result exc...

將shp檔案匯入到mysql資料庫中

shp檔案轉sql檔案 匯入msql 遇到問題 1 將shp以及shp的相關檔案和doshere的doc檔案放在同一目錄 2 doc命令為 shp2mysql shp檔名.shp 表名 資料庫名 生成的sql檔名.sql 3 修改生成的sql檔案 alter table 表名 add the geo...