简体   繁体   English

C#SQL连接问题

[英]C# SQL connection problem

i am using VS.NET 2008 with MS SQL server 2005 to develop a window form application but everytime i got new error in connection or after conected, 我将VS.NET 2008和MS SQL Server 2005一起使用来开发窗口表单应用程序,但是每次我在连接中或连接后遇到新错误时,

in my current code the connection opened but doesnt work after that in transaction of queries. 在我当前的代码中,连接已打开,但此后在查询事务中不起作用。 maybe i have problem while making new DB or new datasource also m not that satisfy how to get Connecting String 也许我在制作新数据库或新数据源时遇到问题也不能满足如何获取连接字符串

this is my code.... 这是我的代码。

/////////
private void button1_Click(object sender, EventArgs e)
    {
        try
        {
            //setData();
            string ConnectingString = @"Data Source=SERVER1\SQLEXPRESS;Initial Catalog=Alkawthar;Integrated Security=True;Pooling=False";
            qry = "SELECT * FROM Table1";
            //reader = db.select_data(qry);
            ds1 = new DataSet();
            conn = new SqlConnection(ConnectingString);

            conn.Open(); 
            MessageBox.Show("connection opened");
            da.Fill(ds1,"Workers");
            NavigateRecords();
            MaxRows = ds1.Tables["Workers"].Rows.Count;
            string sql = "SELECT * From tblWorkers";
            da = new System.Data.SqlClient.SqlDataAdapter(sql, conn);
            conn.Close();
            MessageBox.Show("connection closed");
            conn.Dispose();
        }
        catch (Exception ex)
        {
            MessageBox.Show("exception");
            MessageBox.Show(ex.Message);
        }
    }
/////////////////

Fill throws an exception also when i use reader it return null although there is data in DB thanks 填充也会引发异常,当我使用阅读器时,尽管DB中有数据,但它返回null

The most obvious problem here is that you access the SqlDataAdapter before initializing it. 这里最明显的问题是在初始化之前访问SqlDataAdapter。 That will cause a null reference exception. 这将导致空引用异常。 Try to move the line da = new SqlDataAdapter(...) to the line before you do the da.Fill(...) . 在执行da.Fill(...)之前,请尝试将da = new SqlDataAdapter(...)行移至该行。

Edit: 编辑:

No, wait! 不,等等! I see that you do two queries and two fills in there. 我看到您在其中进行了两个查询和两个填充。 You need to initialize the SqlDataAdapter before doing the first fill. 您需要在执行第一个填充之前初始化SqlDataAdapter。 Then you should get rid of the null reference exception. 然后,您应该摆脱null引用异常。

Edit again: 再次编辑:

Also, as commented, you don't need call both the SqlConnection.Close and SqlConnection.Dispose methods. 同样,如前所述,您不需要同时调用SqlConnection.CloseSqlConnection.Dispose方法。 As long as you use the SqlDataAdapter you don't even need to do the SqlConnection.Open on the connection, for the Fill method will do all that for you. 只要您使用SqlDataAdapter,您甚至都不需要在连接上执行SqlConnection.Open ,因为Fill方法将为您完成所有这些工作。 As long as the connection starts out being closed, the Fill method will close it again for you when it is done. 只要开始关闭连接,Fill方法将在完成连接后再次为您关闭。

Seems to me, that you use your DataAdapter before initialization. 在我看来,您在初始化之前使用了DataAdapter。 Do you get a NullReferenceException ? 你得到一个NullReferenceException吗?

da.Fill(ds1,"Workers"); 
// ...
da = new System.Data.SqlClient.SqlDataAdapter(sql, conn); 

A few points of advice; 几点建议;

  1. Like Turrau and Rune say, your stuff is in the wrong order. 就像Turrau和Rune所说,您的东西顺序错误。 Open connection, Execute SQL - Get raw data, close connection. 打开连接,执行SQL-获取原始数据,关闭连接。 Then do your counting, etc. 然后进行计数等。
  2. Don't put message box or logging calls anywhere in between the connection opening and closing. 在打开和关闭连接之间的任何地方都不要放置消息框或记录呼叫。 This has burned me before, where the those calls can affect the SQL call because they fudge the exception details and make it difficult to trace. 以前,这让我很烦,在那儿那些调用会影响SQL调用,因为它们使异常详细信息变得模糊并且难以跟踪。 This is also applicable when using a SQL data reader. 当使用SQL数据读取器时,这也适用。
  3. Put the SQL stuff in a using block. 将SQL内容放入using块中。

Try this... 尝试这个...

    string _connStr = @"Data Source=SERVER1\SQLEXPRESS;Initial Catalog=Alkawthar;Integrated Security=True;Pooling=False";
    string _query = "SELECT * FROM Workers";
    DataSet _ds = new DataSet();

    try
    {

        using (SqlConnection _conn = new SqlConnection(_connStr))
        {
            SqlDataAdapter _da = new SqlDataAdapter(_query, _conn);
            _conn.Open();
            _da.Fill(_ds);
        }

        // insert null dataset or invalid return logic (too many tables, too few columns/rows, etc here.


        if (_ds.Tables.Count == 1)
        { //There is a table, assign the name to it.
            _ds.Tables[0].TableName = "tblWorkers";
        }

        //Then work with your tblWorkers

    }
    catch (Exception ex)
    {
        Console.Write("An error occurred: {0}", ex.Message);
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM