我必须创建一个数据库,然后在创建的数据库中创建一个表。
我已连接到我的连接字符串上的主,但我想在连接和创建时添加我刚刚在初始目录中创建的新数据库名称桌子。
这就是我所拥有的
string conn = "SERVER=BRIAN-PC\\SQLEXPRESS; Initial Catalog=master; user id =sa; Password=kagiso";
String str = "CREATE DATABASE IF NOT EXIST PSAHoldings ON PRIMARY"
+ "(NAME = PSAHoldings_Data,"
+ "FILENAME = 'C:\\PSAHoldings.mdf'',"
+ "SIZE = 2MB, FILEGROWTH =10%)"
+ "LOG ON (NAME = PSAHoldings_Log,"
+ "FILENAME = 'C:\\PSAHoldingsLog,idf',"
+ "SIZE = 1MB,"
+ "FILEGROTH = 10%)";
SqlConnection connection = new SqlConnection(conn);
connection.Open();
try
{
//SqlCommand to create database
SqlCommand cmd = new SqlCommand(str, connection);
cmd.ExecuteNonQuery();
MessageBox.Show("DataBase was successfully created", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
string connect = "Data Source=Esther-PC\\SQLEXPRESS; Initial Catalog=PSAHoldings; user id =sa; Password=kagiso";
string table = "CREATE TABLE IF NOT EXIST t_original (" +
"empId varChar(10) NOT NULL PRIMARY KEY," +
"paycode varChar(10) NOT NULL," +
"amount int NOT NULL," +
")";
SqlConnection con = new SqlConnection(connect);
con.Open();
SqlCommand createTable = new SqlCommand(table, con);
createTable.ExecuteNonQuery();
}
}
catch (SqlException sqlEx)
{
MessageBox.Show(sqlEx.ToString(), "Exception Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
connection.Close();
con.Close();
}
当我运行应用程序时,我不断出现异常错误。
EXCEPTION ERROR 读取 System.Data.SqlClient.SqlException(0x80131904): Incorrect synax near the keyword 'IF'. expression of non-boolean type specified in a context where a condition is expected, near 'PSAHoldings', Unclosed quotation mark after the character string 'Size=1mb, filegrowth=10%)'.
答案 0 :(得分:1)
我不认为有CREATE DATABASE IF NOT EXIST
这样的代码 - 在MSDN上找不到它的任何提及:
https://msdn.microsoft.com/en-us/library/ms176061.aspx
试试这个。
IF NOT EXISTS (SELECT * FROM sys.databases WHERE name = 'PSAHoldings')
CREATE DATABASE PSAHoldings ON PRIMARY
(NAME = PSAHoldings_Data,
FILENAME = 'C:\\PSAHoldings.mdf',
SIZE = 3MB, FILEGROWTH =10%)
LOG ON (NAME = PSAHoldings_Log,
FILENAME = 'C:\\PSAHoldingsLog.idf',
SIZE = 1MB,
FILEGROWTH = 10%)
(注意其他一些错误类型修复也将文件大小更改为3MB,因为我有一个错误,说它需要至少3MB)
答案 1 :(得分:0)
CREATE DATABASE PSAHoldings ON PRIMARY
(NAME = PSAHoldings_Data,
FILENAME = 'C:\\PSAHoldings.mdf',
SIZE = 2MB, FILEGROWTH =10%)
LOG ON (NAME = PSAHoldings_Log,
FILENAME = 'C:\\PSAHoldingsLog,idf',
SIZE = 1MB,
FILEGROWTH = 10%)
答案 2 :(得分:0)
第一个蓝色突出显示尝试 通过像这样的系统对象搜索数据库
IF NOT EXISTS(SELECT name from sys.databases WHERE name = N' PSAHoldings') / 然后你的创建db脚本到这里 /
红色突出显示我看到两个单引号,应该是1个单引号
检查表格是否已存在
IF NOT EXISTS(SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N' [dbo]。[bbr_categories]')并输入(N' U')) p>
/ 你的创建表脚本到这里 /