Hello, i have solved a challenge of DB connection. Iam now getting this error : system null reference exception when i run this code :
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using System.Data.SqlClient;
- using System.Data;
- using System.Configuration;
- namespace eMarksCollectorLib
- {
- public class dbClass
- {
- private SqlConnection con;
- private SqlCommand com;
- private SqlDataAdapter adapter;
- private DataSet _data;
- public SqlDataReader reader;
- public DataSet Data
- {
- get { return _data; }
- set { _data = value; }
- }
- public dbClass()
- {
-
- adapter = new SqlDataAdapter("", con);
- com = new SqlCommand("", con);
- _data = new DataSet();
- }
- public void Execute(string sql)
- {
- if (con.State == ConnectionState.Closed) con.Open();
- com = new SqlCommand(sql, con);
- com.ExecuteNonQuery();
- con.Close();
- }
- public int ExecuteReturnID(string sql)
- {
-
- if (con.State == ConnectionState.Closed) con.Open();
- com = new SqlCommand(sql, con);
- return Convert.ToInt32(com.ExecuteScalar());
- }
- public DataTable Select(string sql, string table)
- {
-
- adapter.SelectCommand.CommandText = sql;
- adapter.SelectCommand.Connection = con;
- if (_data.Tables.Contains(table))
- {
- _data.Tables.Clear();
- }
- adapter.Fill(_data, table);
- con.Close();
- return _data.Tables[table];
-
- }
- public string ExecuteScalar(string sql)
- {
- string results = "";
- if (con.State == ConnectionState.Closed) con.Open();
- com = new SqlCommand(sql, con);
- results = com.ExecuteScalar().ToString();
- con.Close();
- return results;
- }
- public string ExecuteMyReader(string sql)
- {
- string results = "";
- if (con.State == ConnectionState.Closed) con.Open();
- com = new SqlCommand(sql, con);
- reader = com.ExecuteReader(CommandBehavior.CloseConnection);
- while (reader.Read())
- {
- if (reader[0] != DBNull.Value) results = reader[0].ToString();
- }
- reader.Close();
- con.Close();
- return results;
- }
- public DataTable GetData(string sql, SqlParameter[] sqlParameter)
- {
- DataSet ds = new DataSet();
- SqlCommand cmd = new SqlCommand(sql, con);
- if (sqlParameter != null)
- {
- cmd.Parameters.AddRange(sqlParameter);
- }
- SqlDataAdapter da = new SqlDataAdapter(cmd);
- da.Fill(ds);
- return ds.Tables[0];
- }
- }
- }
the challenge with the code appears at this section :
- public dbClass()
- {
- con = new SqlConnection(ConfigurationManager.ConnectionStrings["con"].ConnectionString);
- adapter = new SqlDataAdapter("", con);
- com = new SqlCommand("", con);
- _data = new DataSet();
- }