开发者

Will this kind of bash work as expected?

#!/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----------------------------------开发者_Python百科---
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;
!
}

Will $MYSQL be persistent across function calls,or reconnect each time?

If it reconnects every time,I don't think create_table_userid will work as expected though,because it hasn't specify a database name yet.


Well, because you will be calling the function each time you want to create the table, you will call mysql to connect to the database each time. If you want persistent connection, one way is to use a mysql library that is supported by most major programming languages these days, Perl/Python/Ruby/PHP etc. You can make a DB connection, then do whatever stuff you want, then finally close the connection. for example in the documentation of 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 ()

As you can see, a connection conn is opened to connect to database. Then using the connection handle (or rather database handle), stuff are done and then finally, the connection is closed.


$MYSQL is just a variable, so your code runs mysql each time it calls one of these functions.

You can create a persistant connection to mysql easily enough; just have your program write its sql to output, then pipe the whole results into mysql:

(
  create_table "foo"
  create_table "bar"
) | mysql

create_table() {
  cat <<!
create table $1 ....
!
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜