Null in C # is not the same as null in SQL, and Null in SQL is represented by C # DBNull.Value
Class Sqlherper
{
private static readonly string connstr = configurationmanager.connectionstrings["ConnStr"]. ConnectionString;
Package execution additions and deletions only returns the number of rows affected when the Insert Updata DELETE statement is executed, and select always returns-1
public static int ExecuteNonQuery (String sql, CommandType cmdtype, params sqlparameter[] parameters)
{
using (SqlConnection conn =new SqlConnection (CONNSTR))
{
using (SqlCommand com = new SqlCommand (SQL, conn))
{
Com.commandtype = Cmdtype;
if (Parameters! = null)
{
foreach (SqlParameter SPR in Parameters)
{
if (SPR. Sqlvalue = = null)
{
SPR. Sqlvalue = DBNull.Value; Null in C # is not the same as null in SQL, and Null in SQL is represented by C # DBNull.Value
}
Com. Parameters.Add (SPR);
}
Com. Parameters.addrange (Parameters);
}
Conn. Open ();
return COM. ExecuteNonQuery ();
}
}
}
Encapsulates a method that returns a single value returns only the first column of the first row
public static Object ExecuteScalar (String sql, CommandType cmdtype, params sqlparameter[] parameters)
{
using (SqlConnection conn = new SqlConnection (CONNSTR))
{
using (SqlCommand com = new SqlCommand (SQL, conn))
{
Com.commandtype = Cmdtype;
if (Parameters! = null)
{
Com. Parameters.addrange (Parameters);
}
Conn. Open ();
return COM. ExecuteScalar ();
}
}
}
Methods to return SqlDataReader objects
public static SqlDataReader ExecuteReader (String sql, CommandType cmdtype, params sqlparameter[] parameters)
{
SqlConnection conn = new SqlConnection (CONNSTR); Connection cannot be enabled by using because the SqlDataReader object is returned when the Conn connection is guaranteed to be open.
using (SqlCommand com = new SqlCommand (SQL, conn))
{
Com.commandtype = Cmdtype;
if (Parameters! = null)
{
Com. Parameters.addrange (Parameters);
}
Try
{
Conn. Open ();
CommandBehavior.CloseConnection The associated Connection object is also closed automatically when the DataReader object is closed.
return COM. ExecuteReader (commandbehavior.closeconnection);
}
catch (Exception)
{
Conn. Dispose ();
Throw
}
}
}
Methods to return a DataTable object
public static DataTable executedatatable (String sql, CommandType cmdtype, params sqlparameter[] parameters)
{
DataTable dt = new DataTable ();
Using (SqlDataAdapter adapter = new SqlDataAdapter (SQL, CONNSTR))
{
Adapter.SelectCommand.CommandType = Cmdtype;
if (Parameters! = null)
{
Adapter. SelectCommand.Parameters.AddRange (Parameters);
}
Adapter. Fill (DT);
}
return DT;
}
}
C # Insert NULL value to database error resolution