连接c#与SQL项目相关的错误

时间:2016-07-14 07:08:04

标签: c# sql-server

我编写了一个C#程序来输出数据库表中包含的内容,但是当我追加conn.open()时,虽然没有任何编译错误,但是没有创建对话框。我已经检查过是否设置了数据库信息,如ip地址,用户名,密码和数据库名称,但是没有任何遗漏。我想知道为什么一旦附加conn.open()就不会执行:

public static string constring = "Data Source= 192.168.0.21; User=root; Password=admin;database=hwg;"; 
SqlConnection conn = new SqlConnection();
private string strConnString = "";

[public void ConnectDB]
strConnString = constring;

if (conn.State.ToString().Equals("Closed"))
{ 
    conn.ConnectionString = strConnString;
    conn.Open();     //problem on this line

    if (conn.State == ConnectionState.Open)
    {
    }
    else
    {
        conn.Close();
    }
}

[public DataTable GetDBTable(string sql)]
SqlDataAdapter adapter = new SqlDataAdapter(sql, conn);
SqlCommandBuilder builder = new SqlCommandBuilder(adapter);
DataTable dt = new DataTable();
adapter.Fill(dt);

return dt;

[public Form1()]
InitializeComponent();
db = new Con_database();
db.ConnectDB();

[private void button1_Click(object sender, EventArgs e)]/*If we click button1, the overall contents of applied table in database hwg is listed*/

   string sql = "SELECT * FROM id_repository";
   DataTable dt = db.GetDBTable(sql);

   DatabaseInquiry.DataSource = dt;
   db.ClosedDB();

1 个答案:

答案 0 :(得分:-1)

我认为您需要在连接字符串中定义USERID而不是USER。

旧连接字符串:

    public static string constring 
= "Data Source= 192.168.0.21; User=root; Password=admin;database=hwg;"; 

新连接字符串:

    public static string constring = 
"Data Source= 192.168.0.21;Initial Catalog="your database name"; UserID=root; Password=admin;";