我遇到了一个棘手的小问题,在这里,它与打开SQL Server数据库
有关主叫代码是
public MainWindow()
{
InitializeComponent();
dbTools = new DataBaseTools();
if (dbTools.DbWorks)
{
label3.Text = "Worked";
}
else
{
label3.Text = "Try Again";
}
label3.AutoSize = true;
}
和连接服务器的代码是
namespace LeatherCorset
{
public class DataBaseTools
{
private Boolean dbWorks;
private SqlConnection myConn;
public DataBaseTools(){
dbWorks = false;
InitialiseDatabase();
}
private void InitialiseDatabase(){
myConn = new SqlConnection();
String ConnString =
"Server=KEITH\\SQLEXPRESS;Database=Corset;Trusted_Connection=Yes";
myConn.ConnectionString = ConnString;
try{
if (myConn.State == ConnectionState.Open){
dbWorks = true;
}
}catch (SqlException ex) {
dbWorks = false;
}
}
public Boolean DbWorks{
get { return dbWorks; }
set { dbWorks = value; }
}
}
}
当我运行调试器时,它会出现connString
,其值为null。
DESKTOP\SQLEXPRESS
Corset
Desktop\Keith
我现在迷失了如何从c#
连接到SQL Server我将不胜感激任何建议和帮助
答案 0 :(得分:2)
我没有看到您使用Open()
打开连接的位置。此外,最好使用正确的字符串初始化SqlConnection
。尝试像
bool dbWorks = false;
sting cs = "Data Source=KIETH\\SQLEXPRESS;Initial Catalog=Corsit;Trusted_Connection=Yes";
using (SqlConnection conn = new SqlConnection(cs))
{
try
{
conn.Open();
if (conn.State == ConnectionState.Open)
{
dbWorks = true;
}
}
}
我希望这会有所帮助。
答案 1 :(得分:2)
看不到ConnString是如何为null,我想你可能有一些调试问题,说,试试这个:
String ConnString = "Server=KEITH\\SQLEXPRESS;Database=Corset;Trusted_Connection=Yes";
using (myConn = new SqlConnection(ConnString)) // This will make sure you actually close the DB
{
myConn.Open(); // You need to open the connection
try
{
if (myConn.State == ConnectionState.Open)
{
dbWorks = true;
}
}
catch (SqlException ex)
{
dbWorks = false;
}
}
我还建议实际取出try / catch,因为你隐藏了一个可能告诉你一切都出错的异常。