简体   繁体   中英

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,

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

The most obvious problem here is that you access the SqlDataAdapter before initializing it. That will cause a null reference exception. Try to move the line da = new SqlDataAdapter(...) to the line before you do the da.Fill(...) .

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. Then you should get rid of the null reference exception.

Edit again:

Also, as commented, you don't need call both the SqlConnection.Close and SqlConnection.Dispose methods. 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. As long as the connection starts out being closed, the Fill method will close it again for you when it is done.

Seems to me, that you use your DataAdapter before initialization. Do you get a 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. Open connection, Execute SQL - Get raw data, close connection. 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. This is also applicable when using a SQL data reader.
  3. Put the SQL stuff in a using block.

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);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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