使用SQL Server的应用程序中的SqlException
本文关键字:SqlException 应用程序 使用 Server SQL | 更新日期: 2023-09-27 17:54:14
嘿,我刚开始学习在c#中使用后端作为sql制作应用程序。我设置了一些断点,以确保控制在执行cntCeilInn.Open();
后永远不会返回很快,输出窗口显示' System.Data.SqlClient.SqlException
'发生在System.Data.dll
谷歌告诉我它不是超时或其他我无法理解的东西。请帮帮我。
string strServerName="EXPRESSION";
using (SqlConnection cntCeilInn = new SqlConnection("Data Source=" + strServerName + ";" + "Integrated Security=YES"))
{
SqlCommand cmdCeilInn= new SqlCommand("If exists ("+ "Select name "+ "from sys.database "+ "Where name=N'CeilInn1')"+ "DROP database CeilInn1;"+ "go"+ "create database CeilInn1;", cntCeilInn);
cntCeilInn.Open();
cmdCeilInn.ExecuteNonQuery();
}
作为connectionString参数,您应该使用:
Data Source=yourServerName;Initial Catalog=yourDatabaseName;Integrated Security=True
确保用适当的数据修改youServerName
和yourDatabaseName
。
注意,您忘记在connectionString(Initial Catalog)中设置数据库名称,并且集成安全性的值为True。
你的sql查询中有几个错误
-
是
sys.databases
不是sys.database
-
Go
和Create
语法之间没有空格 -
您需要将sql语句放在单独的行
-
更不用说检查你的
connection string
一次,因为其他人已经说过
Try this out
SqlCommand cmdCeilInn = new SqlCommand("If exists (" + "Select name " + "from sys.databases " + "Where name=N'Sample') DROP database Sample;"
+Environment .NewLine+ "go " + Environment .NewLine
+" create database Sample;", cntCeilInn);