How to add a using statement in following statement
this.OpenConnection();
SqlParameter[] SqlParameters = {new SqlParameter("#a",A)};
return Convert.ToLong( SqlHelper.ExecuteScalar((SqlConnection)DatabaseConnection, "StoredprocName",SqlParameters).ToString());
Here is an example From MSDN, hope this would help :
static public int AddProductCategory(string newName, string connString)
{
Int32 newProdID = 0;
string sql =
"INSERT INTO Production.ProductCategory (Name) VALUES (#Name); "
+ "SELECT CAST(scope_identity() AS int)";
using (SqlConnection conn = new SqlConnection(connString))
{
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.Add("#Name", SqlDbType.VarChar);
cmd.Parameters["#name"].Value = newName;
try
{
conn.Open();
newProdID = (Int32)cmd.ExecuteScalar();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
return (int)newProdID;
}
More about SqlCommand.ExecuteScalar Method () : https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executescalar(v=vs.110).aspx
Related
I am previously only familiar with Linq and the like for data access. I am working on something now that requires me to use actual SQL commands on the back end to return a single value. My code compiles and runs, however it is returning null for a value that I know should be returning something besides an empty string...
Is my structure off on this? Or is something else missing?
Below is my code:
internal string GetSexDescription(string sex, int id_merchant)
{
string newSex = "";
var builder = new ConnectionStringHelper();
var connString = builder.getCasinoDBString(id_merchant);
using (SqlConnection conn = new SqlConnection(connString))
{
string sql = "SELECT Description FROM person_gender_lookup WHERE ID = #sex";
SqlCommand cmd = new SqlCommand(sql, conn);
try
{
cmd.Parameters.Add("#Sex", SqlDbType.VarChar).Value = sex;
newSex = cmd.ExecuteScalar().ToString();
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
return newSex;
}
}
Here is a picture of the result set of the table:
Open the connection.
internal string GetSexDescription(string sex, int id_merchant)
{
string newSex = "";
var builder = new ConnectionStringHelper();
var connString = builder.getCasinoDBString(id_merchant);
using (SqlConnection conn = new SqlConnection(connString))
{
conn.Open(); //<- This line here.
string sql = "SELECT Description FROM person_gender_lookup WHERE ID = #sex";
SqlCommand cmd = new SqlCommand(sql, conn);
try
{
cmd.Parameters.Add("#Sex", SqlDbType.VarChar).Value = sex;
newSex = cmd.ExecuteScalar().ToString();
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
return newSex;
}
}
cmd.ExecuteScalar() is probably throwing an InvalidOperationException because you haven't opened the connection. The exception is being caught, outputted to the console, then the initial value of newSex is begin returned since the call to ExecuteScalar threw.
ID is a int or varchar?
If is int use:
cmd.Parameters.Add("#sex", SqlDbType.Int).Value = sex;
instead of:
cmd.Parameters.Add("#Sex", SqlDbType.VarChar).Value = sex;
P.S.
Query parameters and parameter add into cmd.Parameters is case sensitive.
Write
#sex
instead of
#Sex
Figured it out. Had to open the cmd and close it AFTER I set the newSex variable to the value being pulled.
internal string GetSexDescription(string sex, int id_merchant)
{
string newSex = "";
var builder = new ConnectionStringHelper();
var connString = builder.getCasinoDBString(id_merchant);
DataSet ds = new DataSet();
using (SqlDataAdapter adapter = new SqlDataAdapter())
{
using (SqlConnection conn = new SqlConnection(connString))
{
string sql = "SELECT Description FROM person_gender_lookup WHERE ID = #Sex";
SqlCommand cmd = new SqlCommand(sql, conn);
try
{
conn.Open();
cmd.Connection = conn;
adapter.SelectCommand = cmd;
cmd.Parameters.Add("#Sex", SqlDbType.VarChar).Value = sex;
adapter.Fill(ds);
newSex = cmd.ExecuteScalar().ToString();
conn.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return newSex;
}
}
}
Try this:
internal string GetSexDescription(string sex, int id_merchant)
{
string newSex = "";
var builder = new ConnectionStringHelper();
var connString = builder.getCasinoDBString(id_merchant);
using (SqlConnection conn = new SqlConnection(connString))
{
string sql = "SELECT Description FROM person_gender_lookup WHERE ID" + sex;;
SqlCommand cmd = new SqlCommand(sql, conn);
try
{
newSex = cmd.ExecuteScalar().ToString();
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
return newSex;
}
}
I'm a beginner programmer with C#. I'm trying to develop an application that it connects to a database and do the typical operations like insert, delete, update and get.
I'm getting a error with the database connection. I'm working with SQL Server 2012, where I have create a database called company.
This is my code:
namespace DAL
{
public class DAL
{
public const string CADENA_CONEXION = "Data Source=localhost;" +
"Initial Catalog=Company" +
"Integrated Security=false" +
"UID=root PWD=root";
public SqlConnection con;
public SqlCommand command;
public DAL()
{
con = new SqlConnection();
con.ConnectionString = CADENA_CONEXION;
}
public Boolean addEmployee(Employee emp)
{
try
{
/*String sqlInsertString = "INSERT INTO Employee (FirstName, LastName, ID, " +
"Designation) VALUES ("+e.firstName+","+ e.lastName+","+e.empCode+","+e.designation+")";*/
string sqlInsertString =
"INSERT INTO Employee (FirstName, LastName, ID, " +
"Designation) VALUES (#firstName, #lastName, #ID, #designation)";
command = new SqlCommand();
command.Connection.Open();
command.CommandText = sqlInsertString;
SqlParameter firstNameparam = new SqlParameter("#firstName", emp.FirstName);
SqlParameter lastNameparam = new SqlParameter("#lastName", emp.LastName);
SqlParameter IDparam = new SqlParameter("#ID", emp.EmpCode);
SqlParameter designationParam = new SqlParameter("#designation", emp.Designation);
command.Parameters.AddRange(new SqlParameter[]{
firstNameparam,lastNameparam,IDparam,designationParam});
command.ExecuteNonQuery();
command.Connection.Close();
return true;
}
catch (Exception ex)
{
return false;
throw;
}
return true;
}
}
What is the error? I get an exception on this line:
command.Connection.Open();
Thanks in advance
SqlConnection con = new SqlConnection("Your Connection String Goes here");
You should assign connection to SqlCommand object like this
SqlCommand command = new SqlCommand();
command.Connection = con;
or
SqlCommand command = new SqlCommand("YourQuery",con);
Some Important Steps to Execute Command
1: Create SqlConnection Object and Assign a connection string to that object
SqlConnection con = new SqlConnection("Your Connection String Goes here");
or
SqlConnection con = new SqlConnection();
con.Connection = "Your Connection String Goes here";
2: Create SqlCommand Object and assing a command Text(Your Query) and connection string to that object
SqlCommand command = new SqlCommand("Select * from Products",con);
or
SqlCommand command = new SqlCommand();
command.Connection = con;
command.CommandText ="Select * from Products";
You can also specify CommandType
command.CommandType =CommandType.Text;
/* if you are executing storedprocedure CommandType Will be
=> CommandType.StoredProcedure; */
then You can Execute Command Like this
try
{
con.Open();
int TotalRowsAffected = command.ExecuteNonQuery();
}
catch(Exeception ex)
{
MessageBox.Show(ex.Message);
}
finaly
{
con.Close();
}
Just an FYI: An alternative to the try finally blocks, which ensure the database connection gets closed is to use the using statement such as:
using (SqlConnection connection = new SqlConnection(
connectionString))
{
try
{
SqlCommand command = new SqlCommand(queryString, connection);
command.Connection.Open();
command.ExecuteNonQuery();
}
catch (InvalidOperationException)
{
//log and/or rethrow or ignore
}
catch (SqlException)
{
//log and/or rethrow or ignore
}
catch (ArgumentException)
{
//log and/or rethrow or ignore
}
}
Refer to the MSDN documentation for the SqlCommand class here, https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.aspx, and look up the ExecuteNonQuery() method, which is used to execute INSERT, UPDATE, and DELETE statements. Then look up ExecuteScalar() method that you can use to execute SELECT statements that return a single value. You can use ExecuteReader() to return a SqlDataReader for SELECT statements that return multiple columns.
not initialize sqlcommand connections, way for initialize this is :
command.Connection=con;
this is complete code for you :
namespace DAL
{
public class DAL
{
public const string CADENA_CONEXION = "Data Source=localhost;" +
"Initial Catalog=Company" +
"Integrated Security=false" +
"UID=root PWD=root";
public SqlConnection con;
public SqlCommand command;
public DAL()
{
con = new SqlConnection();
con.ConnectionString = CADENA_CONEXION;
}
public Boolean addEmployee(Employee emp)
{
try
{
/*String sqlInsertString = "INSERT INTO Employee (FirstName, LastName, ID, " +
"Designation) VALUES ("+e.firstName+","+ e.lastName+","+e.empCode+","+e.designation+")";*/
string sqlInsertString =
"INSERT INTO Employee (FirstName, LastName, ID, " +
"Designation) VALUES (#firstName, #lastName, #ID, #designation)";
command = new SqlCommand();
command.Connection=con;
command.Connection.Open();
command.CommandText = sqlInsertString;
SqlParameter firstNameparam = new SqlParameter("#firstName", emp.FirstName);
SqlParameter lastNameparam = new SqlParameter("#lastName", emp.LastName);
SqlParameter IDparam = new SqlParameter("#ID", emp.EmpCode);
SqlParameter designationParam = new SqlParameter("#designation", emp.Designation);
command.Parameters.AddRange(new SqlParameter[]{
firstNameparam,lastNameparam,IDparam,designationParam});
command.ExecuteNonQuery();
command.Connection.Close();
return true;
}
catch (Exception ex)
{
return false;
throw;
}
return true;
}
}
I am trying to insert a row into the database. Below is my query:
using (SqlConnection conn = new SqlConnection("Data Source = (LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Traindata.mdf;Integrated Security=True"))
{
string query = "INSERT INTO dbo.Station (Naam, X, Y, Sporen) VALUES (#naam, #x, #y, #sporen)";
using (SqlCommand command = new SqlCommand(query, conn))
{
command.Parameters.AddWithValue("#naam", insert[1]);
command.Parameters.AddWithValue("#x", insert[2]);
command.Parameters.AddWithValue("#y", insert[3]);
command.Parameters.AddWithValue("#sporen", insert[4]);
conn.Open();
try
{
command.ExecuteNonQuery();
}
catch (SqlException exc)
{
Console.WriteLine("Error to save on database");
Console.WriteLine(exc.Message);
}
conn.Close();
}
}
When I run it nothing happens (Also no SQL errors). What am I doing wrong? I am sorry if this is a stupid question, I am merely a beginner.
This should work (I have tested this with a select query that does work).
Have you tried storing the query on a stored procedure and calling it from C#? ... Thats actually easier than making the query via hard code inside the C# code ... Just create a stored procedure that does whatever you want it to do, then call it from C# and add the parameters. It should look something like this:
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["Your_Conection_String_s_Name"].ConnectionString);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "dbo.Your_Stored_Procedure";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#Input_Param_1", SqlDbType.VarChar, 18).Value = "C#_Parameter1";
cmd.Parameters.Add("#Input_Param_2", SqlDbType.VarChar, 45).Value = "C#Parameter_2";
cmd.Parameters.Add("#Input_Param_3", SqlDbType.VarChar, 45).Value = "C#Parameter_3";
cmd.Parameters.Add("#Input_Param_4", SqlDbType.Text).Value = "C#Parameter_4";
cmd.Parameters.Add("#Input_Param_5", SqlDbType.VarChar, 45).Value = "C#Parameter_5";
cmd.Parameters.Add("#Output_Parameter_1", SqlDbType.VarChar, 250).Direction = ParameterDirection.Output;
cmd.Parameters.Add("#Output_Parameter_2", SqlDbType.DateTime).Direction = ParameterDirection.Output;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
"C#Output_Parameter_1" = "" + cmd.Parameters["#Output_Parameter_1"].Value;
"C#Output_Parameter_2" = "" + cmd.Parameters["#Output_Parameter_2"].Value;
Hope it helps.
My guess is that you have a type mismatch
If x, y are not int then substitute in the correct type
using (SqlConnection conn = new SqlConnection("Data Source = (LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Traindata.mdf;Integrated Security=True"))
{
using (SqlCommand command = SqlCommand.CreateCommand())
{
try
{
conn.Open();
command.Query = "select count(*) from dbo.Station";
Int32 rowsRet = (Int32)command.ExecuteScalar();
Console.WriteLine(rowsRet.ToString());
command.Query = "INSERT INTO dbo.Station (Naam, X, Y, Sporen) VALUES (#naam, #x, #y, #sporen)";
command.Parameters.AddWithValue("#naam", insert[1]);
command.Parameters.Add("#x", SqlDbType.Int);
command.Parameters["#x"].Value = Int32.Parse(insert[2]);
command.Parameters.Add("#y", SqlDbType.Int);
command.Parameters["#y"].Value = Int32.Parse(insert[3]);
command.Parameters.AddWithValue("#sporen", insert[4]);
rowsRet = command.ExecuteNonQuery();
Console.WriteLine(rowsRet.ToString());
command.Query = "select count(*) from dbo.Station";
Int32 rowsRet = (Int32)command.ExecuteScalar();
Console.WriteLine(rowsRet.ToString());
}
catch (SqlException exc)
{
Console.WriteLine("Error to save on database");
Console.WriteLine(exc.Message);
}
finally
{
conn.Close();
}
// op claims the insert is gone the next time the programs is run
try
{
conn.Open();
command.Query = "select count(*) from dbo.Station";
Int32 rowsRet = (Int32)command.ExecuteScalar();
Console.WriteLine(rowsRet.ToString());
}
catch (SqlException exc)
{
Console.WriteLine("Error to save on database");
Console.WriteLine(exc.Message);
}
finally
{
conn.Close();
}
}
}
I am developing a web application and in the code-behind, I need to get the ID column from specific table in the database and convert it to int. The query is:
string quizID = SELECT MIN(column_name) FROM table_name
and I want to put the value of it in
int quizid
which means I need to conversion, so how to do that?
You're going to want to do something like this:
using (SqlConnection conn=new SqlConnection(sql_string)) {
conn.Open();
SqlCommand command=new SqlCommand(
sql_query,
conn
);
Int32 quizid=((Int32?)command.ExecuteScalar()) ?? 0;
}
int quizID = -1;
using (SqlConnection conn = new SqlConnection(connString))
{
conn.Open();
string cmdText = "SELECT MIN(column_name) FROM table_name";
using (SqlCommand cmd = new SqlCommand(cmdText, conn))
{
SqlDataReader reader = cmd.ExecuteReader();
if (reader != null)
{
while (reader.Read())
{
quizID = reader.GetInt32("columnname");
}
}
reader.Close();
}
conn.Close();
}
SqlCommand cmd = new SqlCommand("SELECT MIN(column_name) FROM table_name", conn);
try
{
conn.Open();
int quizid = (Int32)cmd.ExecuteScalar();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
conn is the SqlConnection object
Can anybody give an example for executing a T-SQL statement using C#?
Do you mean something like this:
private static void ReadOrderData(string connectionString)
{
string commandText = "SELECT OrderID, CustomerID FROM dbo.Orders;";
using (SqlConnection connection = new SqlConnection(connectionString))
{
using (SqlCommand command = new SqlCommand(commandText, connection))
{
connection.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
Console.WriteLine(String.Format("{0}, {1}",
reader[0], reader[1]));
}
}
}
}
}
Or, perhaps something like:
static public int AddProductCategory(string newName, string connString)
{
Int32 newProdID = 0;
string sql =
"INSERT INTO Production.ProductCategory (Name) VALUES (#Name); "
+ "SELECT CAST(scope_identity() AS int)";
using (SqlConnection conn = new SqlConnection(connString))
{
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.Add("#Name", SqlDbType.VarChar);
cmd.Parameters["#Name"].Value = newName;
try
{
conn.Open();
newProdID = (Int32)cmd.ExecuteScalar();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
return (int)newProdID;
}
Source: MSDN
I suggest that you start with an ADO.NET turorial like this one
http://www.csharp-station.com/Tutorials/AdoDotNet/Lesson01.aspx
How to use SQLCommand
http://www.csharp-station.com/Tutorials/AdoDotNet/Lesson03.aspx
Using a reader:
SqlConnection MSSQLConn = new SqlConnection("your connection string");
MSSQLConn.Open();
SqlCommand MSSQLSelectConsignment = new SqlCommand();
MSSQLSelectConsignment.CommandText = "select * from yourtable where blah = #blah";
MSSQLSelectConsignment.Parameters.AddWithValue("#blah", somestring);
MSSQLSelectConsignment.Connection = MSSQLConnOLD;
SqlDataReader reader = MSSQLSelectConsignment.ExecuteReader();
while (reader.Read())
{
...
}
To bring back a single value:
MSSQLSelectConsignment.CommandText = "select fieldname from yourtable where blah = #blah";
string yourstring = MSSQLSelectConsignment.ExecuteScalar().ToString();
or to bring back number of rows affected for updates etc:
MSSQLSelectConsignment.CommandText = "update yourtable set yourfield = 0 where blah = #blah";
int yourint = MSSQLSelectConsignment.ExecuteNonQuery();
Hope helps :)