大家好 写一个项目并遇到一个问题 代码:
private SqlConnection scon;
private SqlCommand scom;
string defConnection =
"Data Source=" + Environment.MachineName + @"\SQLEXPRESS;" +
"Integrated security=true;" +
"database=dbTrash";
string altConnection =
"Data Source=" + Environment.MachineName + @"\SQLEXPRESS;" +
"Integrated security=SSPI;" +
"database=master";
/// <summary>
/// Constructor, trying connect to DB
/// </summary>
public DB()
{
scon = new SqlConnection(defConnection);
try
{
scon.Open();
}
catch (Exception ex)
{
MessageBox.Show("Не удалось создать подключение к БД\n"+
"Будет созданая новая БД, инструкцию прочтите в справке\nПричина: " +ex.Message, "Сообщение" );
try
{
// dbTrash exist, trying connect to db master, succesfully!
SqlConnection myConn = new SqlConnection(altConnection);
// create MY db - dbTrash
SqlCommand myCommand = new SqlCommand(createDB, myConn);
try
{
myConn.Open();
myCommand.ExecuteNonQuery();
}
catch (System.Exception x)
{
MessageBox.Show(x.Message, "Сообщение");
}
finally
{
if (myConn.State == ConnectionState.Open)
{
myConn.Close();
}
}
}
catch (Exception e)
{
MessageBox.Show("Не удалось создать новую БД\nПричина: " + e.Message, "Сообщение");
}
// trying connect to dbTrash
// AND NOTHING. ERROR - CAN'T CONNECT TO DB, 'CAUSE EXIST dbTrash!!!!!!!!!!!!
SqlConnection scon1 = new SqlConnection(defConnection);
// create tables in DB but nothin'
SqlCommand scom1 = new SqlCommand(createTables, scon1);
scon1.Open();
}
}
const string createDB = "create database dbTrash";
/// <summary>
///
/// </summary>
const string createTables = "create table [dbo].[Types] (" +
"id int not null," +
"types nvarchar(15) not null," +
"primary key (id)" +
") GO " +
"create table Files (" +
"id int not null," +
"nameOfFile nvarchar(50) not null," +
"fileSizeInByte int not null," +
"fileSize float not null," +
"typeId int not null," +
"tags nvarchar(200)," +
"filePath nvarchar(60) unique not null," +
"xml nvarchar(300)," +
"primary key (id)," +
"foreign key (typeId) references Types(id)" +
"); GO";
如何在dbTrash中编写表格,如果(阅读代码)!
答案 0 :(得分:0)
问题可能是命令的顺序
SqlConnection scon1 = new SqlConnection(defConnection);
// create tables in DB but nothin'
SqlCommand scom1 = new SqlCommand(createTables, scon1);
scon1.Open();
在针对该连接运行命令之前,是否应该打开连接?
答案 1 :(得分:0)
是否正在创建dbTrash数据库?
另外,确保GO语句各自都在其自己的行上。
同时拨打ExecuteNonQuery()
.....
// AND NOTHING. ERROR - CAN'T CONNECT TO DB, 'CAUSE EXIST dbTrash!!!!!!!!!!!!
SqlConnection scon1 = new SqlConnection(defConnection);
// create tables in DB but nothin'
SqlCommand scom1 = new SqlCommand(createTables, scon1);
scon1.Open();
scom1.ExecuteNonQuery(); //call this