#!/bin/bash
MYSQL="/usr/bin/mysql -uroot "
function create_db()
{
local db_name=${1}
$MYSQL<<!
create database IF NOT EXISTS ${db_name};
!
}
###-------------------------tb_bind_userid_xxx-------------------------------------
function create_table_userid
{
$MYSQL << !
create table if NOT EXISTS bind_pay.tb_bind_userid_${1}(
b_userid bigint not null,
b_membercode bigint not null ,
PRIMARY KEY (b_userid)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
!
}
$MYSQL
会在函数调用之间保持持久性,还是每次都重新连接?
如果每次都重新连接,我认为create_table_userid
不会按预期工作,因为它尚未指定数据库名称。
答案 0 :(得分:2)
好吧,因为每次要创建表时都会调用该函数,所以每次都会调用mysql
来连接数据库。如果你想要持久连接,一种方法是使用目前大多数主流编程语言支持的mysql库,Perl / Python / Ruby / PHP等。你可以建立数据库连接,然后做你想做的任何事情,最后关闭连接。例如,在Python/Mysql
import MySQLdb
conn = MySQLdb.connect (host = "localhost",
user = "testuser",
passwd = "testpass",
db = "test")
cursor = conn.cursor ()
cursor.execute ("SELECT VERSION()")
row = cursor.fetchone ()
print "server version:", row[0]
cursor.close ()
conn.close ()
如您所见,打开了连接conn
以连接到数据库。然后使用连接句柄(或者更确切地说是数据库句柄)完成工作,然后最后关闭连接。
答案 1 :(得分:0)
$MYSQL
只是一个变量,因此每次调用其中一个函数时,代码都会运行 mysql。
你可以轻松地创建与mysql的持久连接;只需让你的程序将其sql写入输出,然后将整个结果传递给mysql:
(
create_table "foo"
create_table "bar"
) | mysql
create_table() {
cat <<!
create table $1 ....
!
}