是否可以在建立连接后检查MySQL数据库是否存在。
我知道如何检查一个表是否存在于一个DB,但我需要检查DB是否存在。如果不是,我必须调用另一段代码来创建它并填充它。
我知道这一切听起来有点不优雅-这是一个快速和肮脏的应用程序。
是否可以在建立连接后检查MySQL数据库是否存在。
我知道如何检查一个表是否存在于一个DB,但我需要检查DB是否存在。如果不是,我必须调用另一段代码来创建它并填充它。
我知道这一切听起来有点不优雅-这是一个快速和肮脏的应用程序。
当前回答
Golang解决方案
创建一个测试包并添加:
import "database/sql"
// testing database creation
func TestCreate(t *testing.T){
Createdb("*Testdb") // This just calls the **sql.DB obect *Testdb
db,err := sql.Open("mysql", "root:root@tcp(127.0.0.1:3306)/*Testdb")
if err != nil{
panic(err)
}
defer db.Close()
_, err = db.Exec("USE *Testdb")
if err != nil{
t.Error("Database not Created")
}
}
其他回答
下面是一个bash函数,用于检查数据库是否存在:
function does_db_exist {
local db="${1}"
local output=$(mysql -s -N -e "SELECT schema_name FROM information_schema.schemata WHERE schema_name = '${db}'" information_schema)
if [[ -z "${output}" ]]; then
return 1 # does not exist
else
return 0 # exists
fi
}
另一种选择是尝试使用数据库。注意,这也检查权限:
if mysql "${db}" >/dev/null 2>&1 </dev/null
then
echo "${db} exists (and I have permission to access it)"
else
echo "${db} does not exist (or I do not have permission to access it)"
fi
CREATE SCHEMA IF NOT EXISTS `demodb` DEFAULT CHARACTER SET utf8 ;
检查数据库是否存在的一个简单方法是:
SHOW DATABASES LIKE 'dbname';
如果名称为'dbname'的数据库不存在,则得到一个空集。如果它存在,就得到一行。
SELECT COUNT(*) FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = 'DbName'
1 -存在,0 -不存在
检查PHP中是否存在数据库的一个好方法是:
$mysql = mysql_connect("<your host>", "root", "");
if (mysql_select_db($mysql, '<your db name>')) {
echo "Database exists";
} else {
echo "Database does not exist";
}
这是我常用的方法。