While trying to covert Mssql code to MySQL, specifically during a MysqlCommand request I have created CS1026, CS1002 and a CS1513 error codes,
here is the Mssql code:
try
{
sqlConnect = new System.Data.SqlClient.SqlConnection("server=" + SQLServerAddress + "," + SQLServerPort + "; initial catalog=" + DatabaseName + "; Integrated Security=SSPI");
sqlConnect.Open();
System.Data.SqlClient.SqlCommand sqlCmd = new System.Data.SqlClient.SqlCommand("SELECT ImageFileName, FacePositionXc, FacePositionYc, FacePositionW, FacePositionAngle, Eye1X, Eye1Y, Eye2X, Eye2Y, Template, Image, FaceImage FROM FaceList", sqlConnect);
System.Data.SqlClient.SqlDataReader reader = sqlCmd.ExecuteReader();
while (reader.Read())
I tried to translate this to MySQL as:
string conn = "server=localhost; uid=user;" +
"pwd=password; database=database;";
MySqlConnection connection = new MySqlConnection(conn);
connection.Open();
try
{
MySqlCommand cmd = connection.CreateCommand();
cmd.Connection = connection;
cmd.CommandText = ("SELECT ImageFileName, FacePositionXc, FacePositionYc, FacePositionW, FacePositionAngle, Eye1X, Eye1Y, Eye2X, Eye2Y, Template, Image, FaceImage FROM faces", connection);
MySqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
TFaceRecord fr = new TFaceRecord();
fr.ImageFileName = reader.GetString(4);
fr.FacePosition = new FSDK.TFacePosition();
fr.FacePosition.xc = reader.GetInt32(5);
fr.FacePosition.yc = reader.GetInt32(6);
fr.FacePosition.w = reader.GetInt32(7);
fr.FacePosition.angle = reader.GetFloat(8);
fr.FacialFeatures = new FSDK.TPoint[2];
fr.FacialFeatures[0] = new FSDK.TPoint();
fr.FacialFeatures[0].x = reader.GetInt32(9);
fr.FacialFeatures[0].y = reader.GetInt32(10);
fr.FacialFeatures[1] = new FSDK.TPoint();
fr.FacialFeatures[1].x = reader.GetInt32(11);
fr.FacialFeatures[1].y = reader.GetInt32(12);
fr.Template = new byte[FSDK.TemplateSize];
reader.GetBytes(9, 0, fr.Template, 0, FSDK.TemplateSize);
Image img = Image.FromStream(new System.IO.MemoryStream(reader.GetInt32(14)));
Image img_face = Image.FromStream(new System.IO.MemoryStream(reader.GetInt32(15)));
fr.image = new FSDK.CImage(img);
fr.faceImage = new FSDK.CImage(img_face);
FaceList.Add(fr);
imageList1.Images.Add(fr.faceImage.ToCLRImage());
string fn = fr.ImageFileName;
listView1.Items.Add((imageList1.Images.Count - 1).ToString(), fn.Split('\\')[fn.Split('\\').Length - 1], imageList1.Images.Count - 1);
textBox1.Text += "File '" + fn + "' read from database\r\n";
img.Dispose();
img_face.Dispose();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Exception on loading database");
}
finally
{
if (connection.State == ConnectionState.Open)
{
connection.Close();
// LoadData();
}
}
}
The error is generated at the end of the command text ' ", connection ) '
Removing the ', connection' creates a 'Unable to cast object of type ‘symbol.Byte[] to type ‘System.Convertable’' on the error exception.
Could anyone please advise on the correct syntax to use or where my mistake is thank you.
Related
MySql.Data.MySqlClient.MySqlException: 'You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'order' at line 1'"
my get and post methods in my web api are not working but all the other get methods for the other classes are working and they apply the same principle i get the error form above
my code is as follows:
public long saveOrder(Order o)
{
//creating connection string and linking it to the db
MySql.Data.MySqlClient.MySqlConnection connection;
string connString = ConfigurationManager.ConnectionStrings["dblocal"].ConnectionString;
connection = new MySql.Data.MySqlClient.MySqlConnection();
try
{
//opening the connection
connection.ConnectionString = connString;
connection.Open();
String strsql = "INSERT INTO order (user_id_order,order_date,order_status,product_id_order,car_regplate,estimated_arrival,supplier_id_order,driver_id_order) VALUES(" + o.User_Id_Order + ",'" + o.Order_Date.ToString("yyyy-MM-dd HH:mm:ss") + "','" + o.Order_Status + "'," + o.Product_Id_Order + ",'" + o.Car_RegPlate + "','" + o.Estimated_Arrival.ToString("yyyy-MM-dd HH:mm:ss") + "'," + o.Supplier_Id_Order + "," + o.Driver_Id_Order + ")";
MySql.Data.MySqlClient.MySqlCommand command = new MySql.Data.MySqlClient.MySqlCommand(strsql, connection);
command.ExecuteNonQuery();
long cId = command.LastInsertedId;
return cId;
}
catch (MySql.Data.MySqlClient.MySqlException e)
{
throw e;
}
finally
{
connection.Close();
}
}
//helper method for GET
//function to retrieve a user from the db using select statement
public Order getOrder(long id)
{
//creating connection string and linking it to the db
MySql.Data.MySqlClient.MySqlConnection connection;
string connString = ConfigurationManager.ConnectionStrings["dblocal"].ConnectionString;
connection = new MySql.Data.MySqlClient.MySqlConnection();
try
{
//opening connection
connection.ConnectionString = connString;
connection.Open();
Order o = new Order();
//declaration of reader
MySql.Data.MySqlClient.MySqlDataReader reader = null;
String strsql = "";
//select statement to select what we are retrieving
strsql = "SELECT * FROM order WHERE order_id = " + id.ToString();
//command for connection
MySql.Data.MySqlClient.MySqlCommand command = new MySql.Data.MySqlClient.MySqlCommand(strsql, connection);
//retrieves what comes back form execute reader
reader = command.ExecuteReader();
if (reader.Read())
{
//gets the first integer that came back and assigns it to user id
o.Order_Id = reader.GetInt32(0);
o.User_Id_Order = reader.GetInt32(1);
o.Order_Date = reader.GetDateTime(2);
o.Order_Status = reader.GetString(3);
o.Product_Id_Order = reader.GetInt32(4);
o.Car_RegPlate = reader.GetString(5);
o.Estimated_Arrival = reader.GetDateTime(6);
o.Supplier_Id_Order = reader.GetInt32(7);
o.Driver_Id_Order = reader.GetInt32(8);
return o;
}
else
{
return null;
}
}
catch (MySql.Data.MySqlClient.MySqlException e)
{
throw e;
}
finally
{
connection.Close();
}
}
//helper method for GET
//function to retrieve all users from the db using select statement
public ArrayList getOrders()
{
//creating connection string and linking it to the db
MySql.Data.MySqlClient.MySqlConnection connection;
string connString = ConfigurationManager.ConnectionStrings["dblocal"].ConnectionString;
connection = new MySql.Data.MySqlClient.MySqlConnection();
try
{
//opening the connection
connection.ConnectionString = connString;
connection.Open();
ArrayList oArraylist = new ArrayList();
//declaration of reader
MySql.Data.MySqlClient.MySqlDataReader reader = null;
String strsql = "";
//select statement to select what we are retrieving
strsql = "SELECT * FROM order";
//command for connection
MySql.Data.MySqlClient.MySqlCommand command = new MySql.Data.MySqlClient.MySqlCommand(strsql, connection);
//retrieves what comes back form execute reader
reader = command.ExecuteReader();
while (reader.Read())
{
Order o = new Order();
//gets the first integer that came back and assigns it to user id
o.Order_Id = reader.GetInt32(0);
o.User_Id_Order = reader.GetInt32(1);
o.Order_Date = reader.GetDateTime(2);
o.Order_Status = reader.GetString(3);
o.Product_Id_Order = reader.GetInt32(4);
o.Car_RegPlate = reader.GetString(5);
o.Estimated_Arrival = reader.GetDateTime(6);
o.Supplier_Id_Order = reader.GetInt32(7);
o.Driver_Id_Order = reader.GetInt32(8);
oArraylist.Add(o);
}
return oArraylist;
}
catch (MySql.Data.MySqlClient.MySqlException e)
{
throw e;
}
finally
{
connection.Close();
}
}
So i am quite new to programing overall but i am learning pretty quick, so what im stuck on right now is that i need to read from a SQL table but i only want to read a single row by a key inside of the database.
The code i have down here does the work but i am quite sure you can do this alot more smooth as this is not very clean.
How could i do this in another more simple way?
What i want for result is to add all rows in to their own strings so that i can more easy use them for labels and other information in my program.
private static MySqlConnection dbConn;
static string MySQLConnectionString = "Server='ip';Port='port';Database='name';User='user';Password='Password';SslMode='none'";
public static void InitializeDB()
{
dbConn = new MySqlConnection(MySQLConnectionString);
string commandSuperuser = "SELECT * FROM sl WHERE User=(1)";
string commandUserOne = "SELECT * FROM sl WHERE User=(1)";
string commandUserTwo = "SELECT * FROM sl WHERE User=(2)";
string commandUserThree = "SELECT * FROM sl WHERE User=(3)";
string commandUserFour = "SELECT * FROM sl WHERE User=(4)";
string commandUserFive = "SELECT * FROM sl WHERE User=(5)";
string commandUserSix = "SELECT * FROM sl WHERE User=(6)";
string commandUserSeven = "SELECT * FROM sl WHERE User=(7)";
string commandUserEight = "SELECT * FROM sl WHERE User=(8)";
MySqlCommand cmd1 = new MySqlCommand(commandSuperuser, dbConn);
dbConn.Open();
MySqlDataReader reader1 = cmd1.ExecuteReader();
while (reader1.Read())
{
UserSuperuserName = reader1["Name"].ToString() + " " + reader1["Lastname"].ToString();
UserSuperuserENumber = reader1["ENumber"].ToString();
UserSuperuserNumber = reader1["Number"].ToString();
UserSuperuserNickname = reader1["Nickname"].ToString();
UserSuperuserMail = reader1["Email"].ToString();
}
dbConn.Close();
MySqlCommand cmd2 = new MySqlCommand(commandUserOne, dbConn);
dbConn.Open();
MySqlDataReader reader2 = cmd2.ExecuteReader();
while (reader2.Read())
{
UserOneName = reader2["Name"].ToString() + " " + reader2["Lastname"].ToString();
UserOneENumber = reader2["ENumber"].ToString();
UserOneNumber = reader2["Number"].ToString();
UserOneNickname = reader2["Nickname"].ToString();
UserOneMail = reader2["Email"].ToString();
}
dbConn.Close();
MySqlCommand cmd3 = new MySqlCommand(commandUserTwo, dbConn);
dbConn.Open();
MySqlDataReader reader3 = cmd3.ExecuteReader();
while (reader3.Read())
{
UserTwoName = reader3["Name"].ToString() + " " + reader3["Lastname"].ToString();
UserTwoENumber = reader3["ENumber"].ToString();
UserTwoNumber = reader3["Number"].ToString();
UserTwoNickname = reader3["Nickname"].ToString();
UserTwoMail = reader3["Email"].ToString();
}
dbConn.Close();
MySqlCommand cmd4 = new MySqlCommand(commandUserThree, dbConn);
dbConn.Open();
MySqlDataReader reader4 = cmd4.ExecuteReader();
while (reader4.Read())
{
UserThreeName = reader4["Name"].ToString() + " " + reader4["Lastname"].ToString();
UserThreeENumber = reader4["ENumber"].ToString();
UserThreeNumber = reader4["Number"].ToString();
UserThreeNickname = reader4["Nickname"].ToString();
UserThreeMail = reader4["Email"].ToString();
}
dbConn.Close();
MySqlCommand cmd5 = new MySqlCommand(commandUserFour, dbConn);
dbConn.Open();
MySqlDataReader reader5 = cmd5.ExecuteReader();
while (reader5.Read())
{
UserFourName = reader5["Name"].ToString() + " " + reader5["Lastname"].ToString();
UserFourENumber = reader5["ENumber"].ToString();
UserFourNumber = reader5["Number"].ToString();
UserFourNickname = reader5["Nickname"].ToString();
UserFourMail = reader5["Email"].ToString();
}
dbConn.Close();
MySqlCommand cmd6 = new MySqlCommand(commandUserFive, dbConn);
dbConn.Open();
MySqlDataReader reader6 = cmd6.ExecuteReader();
while (reader6.Read())
{
UserFiveName = reader6["Name"].ToString() + " " + reader6["Lastname"].ToString();
UserFiveENumber = reader6["ENumber"].ToString();
UserFiveNumber = reader6["Number"].ToString();
UserFiveNickname = reader6["Nickname"].ToString();
UserFiveMail = reader6["Email"].ToString();
}
dbConn.Close();
MySqlCommand cmd7 = new MySqlCommand(commandUserSix, dbConn);
dbConn.Open();
MySqlDataReader reader7 = cmd7.ExecuteReader();
while (reader7.Read())
{
UserSixName = reader7["Name"].ToString() + " " + reader7["Lastname"].ToString();
UserSixENumber = reader7["ENumber"].ToString();
UserSixNumber = reader7["Number"].ToString();
UserSixNickname = reader7["Nickname"].ToString();
UserSixMail = reader7["Email"].ToString();
}
dbConn.Close();
MySqlCommand cmd8 = new MySqlCommand(commandUserSeven, dbConn);
dbConn.Open();
MySqlDataReader reader8 = cmd8.ExecuteReader();
while (reader8.Read())
{
UserSevenName = reader8["Name"].ToString() + " " + reader8["Lastname"].ToString();
UserSevenENumber = reader8["ENumber"].ToString();
UserSevenNumber = reader8["Number"].ToString();
UserSevenNickname = reader8["Nickname"].ToString();
UserSevenMail = reader8["Email"].ToString();
}
dbConn.Close();
MySqlCommand cmd9 = new MySqlCommand(commandUserEight, dbConn);
dbConn.Open();
MySqlDataReader reader9 = cmd9.ExecuteReader();
while (reader9.Read())
{
UserEightName = reader9["Name"].ToString() + " " + reader9["Lastname"].ToString();
UserEightENumber = reader9["ENumber"].ToString();
UserEightNumber = reader9["Number"].ToString();
UserEightNickname = reader9["Nickname"].ToString();
UserEightMail = reader9["Email"].ToString();
}
dbConn.Close();
}
If someone has any tips/examples that would be awesome.
You could use MysqlDataAdapter and DataTable and save the values to String arrays.
public static void InitializeDB()
{
dbConn = new MySqlConnection(MySQLConnectionString);
dbConn.Open();
try
{
using (MySqlDataAdapter da = new MySqlDataAdapter("SELECT * FROM S1", dbConn))
{
DataTable dt = new DataTable();
da.Fill(dt);
int a = 0;
if (dt.Rows.Count > 0)
{
string[] UserName = new string[dt.Rows.Count];
string[] UserENumber = new string[dt.Rows.Count];
string[] UserNumber = new string[dt.Rows.Count];
string[] UserNickname = new string[dt.Rows.Count];
string[] UserMail = new string[dt.Rows.Count];
for (a = 0; a < dt.Rows.Count; a++)
{
UserName[a] = dt.Rows[a]["Name"].ToString();
UserENumber[a] = dt.Rows[a]["Enumber"].ToString();
UserNumber[a] = dt.Rows[a]["Number"].ToString();
UserNickname[a] = dt.Rows[a]["Nickname"].ToString();
UserMail[a] = dt.Rows[a]["Mail"].ToString();
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
dbConn.Close();
}
}
There are many questions similar to my issue,but none of them helped away from this issue..
I'm working with win-forms, coding in C#, using SQL server
I have a datagridview which is retrieving data from database with some data as text and some are images.
My code is as given below to save the datagridview data to database
but this is not working and throwing an error an object or column name is missing or empty. for select into statements verify ..........
Please solve my issue..
try
{
ConnectionStringSettings consettings = ConfigurationManager.ConnectionStrings["attendancemanagement"];
string connectionString = consettings.ConnectionString;
string StrQuery;
try
{
using (SqlConnection conn = new SqlConnection(connectionString))
{
using (SqlCommand comm = new SqlCommand())
{
comm.Connection = conn;
conn.Open();
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
StrQuery = #"INSERT INTO dailydemo VALUES ("
+ dataGridView1.Rows[i].Cells["S_No"].Value + ", "
+ dataGridView1.Rows[i].Cells["Employee_Id"].Value + ", "
+ dataGridView1.Rows[i].Cells["Employee_Name"].Value + ", "
+ dataGridView1.Rows[i].Cells["In_time"].Value + ", "
+ dataGridView1.Rows[i].Cells["Out_Time"].Value + ", "
+ dataGridView1.Rows[i].Cells["Date"].Value + ", "
+ dataGridView1.Rows[i].Cells["Week_No_of_The_Month"].Value + ", "
+ dataGridView1.Rows[i].Cells["Attendance"].Value + ", "
+ dataGridView1.Rows[i].Cells["Work_status"].Value + ", "
+ dataGridView1.Rows[i].Cells["Remarks"].Value + ", "
+ dataGridView1.Rows[i].Cells["Image_of_Employee"].Value + ");";
comm.CommandText = StrQuery;
comm.ExecuteNonQuery();
}
}
}
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
Use this may be Help full...
byte[] imgByteArrLogo = new byte[0];
using (SqlConnection con = new SqlConnection("Your Connection string Here"))
{
if (con.State == ConnectionState.Closed)
{
con.Open();
}
using (SqlTransaction _pTrans = con.BeginTransaction(IsolationLevel.ReadCommitted))
{
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
if (dataGridView1.Rows[i].Cells["Image_of_Employee"].Value != null)
{
Image _dgvImage = (Image)dataGridView1.Rows[i].Cells["Image_of_Employee"].Value;
MemoryStream ms = new MemoryStream();
_dgvImage.Save(ms, ImageFormat.Jpeg);
imgByteArrLogo = new byte[ms.Length];
ms.Position = 0;
ms.Read(imgByteArrLogo, 0, imgByteArrLogo.Length);
}
else
{
imgByteArrLogo = new byte[0];
}
try
{
string sql = "INSERT INTO dailydemo (S_No,Employee_Id ,Employee_Name ,In_time ,Out_Time ,Date,Week_No_of_The_Month,Attendance,Work_status,Remarks,Image_of_Employee) VALUES (#S_No,#Employee_Id ,#Employee_Name ,#In_time ,#Out_Time ,#Date,#Week_No_of_The_Month,#Attendance,#Work_status,#Remarks,#Image_of_Employee)";
using (SqlCommand cmd = new SqlCommand(sql, con, _pTrans))
{
cmd.Parameters.Add(new SqlParameter("#S_No", dataGridView1.Rows[i].Cells["S_No"].Value));
cmd.Parameters.Add(new SqlParameter("#Employee_Id", dataGridView1.Rows[i].Cells["Employee_Id"].Value));
cmd.Parameters.Add(new SqlParameter("#Employee_Name", dataGridView1.Rows[i].Cells["Employee_Name"].Value));
cmd.Parameters.Add(new SqlParameter("#In_time", dataGridView1.Rows[i].Cells["In_time"].Value));
cmd.Parameters.Add(new SqlParameter("#Out_Time", dataGridView1.Rows[i].Cells["Out_Time"].Value));
cmd.Parameters.Add(new SqlParameter("#Week_No_of_The_Month", dataGridView1.Rows[i].Cells["Week_No_of_The_Month"].Value));
cmd.Parameters.Add(new SqlParameter("#Attendance", dataGridView1.Rows[i].Cells["Attendance"].Value));
cmd.Parameters.Add(new SqlParameter("#Work_status", dataGridView1.Rows[i].Cells["Work_status"].Value));
cmd.Parameters.Add(new SqlParameter("#Remarks", dataGridView1.Rows[i].Cells["Remarks"].Value));
cmd.Parameters.Add(new SqlParameter("#Image_of_Employee", imgByteArrLogo));
cmd.ExecuteScalar();
}
}
catch (Exception exp)
{
_pTrans.Rollback();
con.Close();
_pTrans.Dispose();
MessageBox.Show(exp.Message, "Error!!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
_pTrans.Commit();
_pTrans.Dispose();
con.Close();
}
}
UPDATE :
Please note that in this example I used your datagridview cell name as sql table column names, if column names are diffrent then modify it.
I have to retrieve the names and the schemas of old tables for creating the new tables in new database within a program. I wrote this procedure which is working. In first part I get the names of tables and store it in MyArray and the in second part I put this names in query string. But in the second part I get in first read the name of table and the following data is the schema.
Is there a solution like this:(this is not working I tried :)
MySqlCommand cmd = new MySqlCommand("SHOW * CREATE TABLE " + DbName, conn);
My function is there:
private int CopySchemas(string pathname)
{
string [] MyArray = new string[11];
int index = 0;
using (MySqlConnection conn = new MySqlConnection(connstr))
{
using(MySqlCommand cmd = new MySqlCommand("SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE' AND TABLE_SCHEMA='" + DbName+"'",conn))
{
conn.Open();
try
{
MySqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
MyArray[index] = reader.GetValue(0).ToString();
++index;
}
reader.Dispose();
}
catch (MySqlException e)
{
MessageBox.Show(e.Number.ToString() + " -> " + e.Message.ToString());
return 0;
}
}
for (int i = 0; i < MyArray.Length; ++i)
{
string tblname = MyArray[i];
string fname = pathname +"\\" + tblname + ".sql";
MySqlCommand cmd = new MySqlCommand("SHOW CREATE TABLE " + DbName + "." + tblname, conn);
MySqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
string fname = pathname +"\\" + reader.GetValues(0) + ".sql";
string schema = reader.GetValue(1).ToString();
File.WriteAllText(fname,schema);
}
reader.Dispose();
}
}
return index;
}
Finally I sawed that for each connection must have only one reader.
So I opened two connections and for each connection I associated a reader. So I don't use an array for storing the tables names I use only the second reader where I get the tables names and schemas.
Here is the code:
private int CopySchemas(string pathname)
{
int index = 0;
MySqlConnection conn1 = new MySqlConnection(PublicVariables.cs);
using (MySqlConnection conn = new MySqlConnection(PublicVariables.cs))
{
using (MySqlCommand cmd = new MySqlCommand("SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE' AND TABLE_SCHEMA='" + PublicVariables.DbName + "'", conn))
{
conn.Open();
conn1.Open();
try
{
MySqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
string tblname = reader.GetValue(0).ToString();
MySqlCommand cmd1 = new MySqlCommand("SHOW CREATE TABLE " + PublicVariables.DbName + "." + tblname, conn1);
MySqlDataReader reader1 = cmd1.ExecuteReader();
while (reader1.Read())
{
string fname = pathname + "\\" + reader1.GetValue(0).ToString() + ".sql";
string schema = reader1.GetValue(1).ToString();
File.WriteAllText(fname, schema);
}
reader1.Dispose();
++index;
}
}
catch (MySqlException e)
{
MessageBox.Show(e.Number.ToString() + " -> " + e.Message.ToString());
return 0;
}
}
}
return index;
}
How do I pass a stored procedure along with parameters as a string to a function?
I tried this code but no luck..
This is the Business Access Layer code
try
{
string Query_string = "SP_InsertOffer_Tab #offer_name ='" + this.offer_name +"', #offer_price = " + this.offer_price + ",#start_date = '" + this.start_date +
"',#end_date = '" + this.end_date + "'";
int result = DbAcess.Insert_Query(Query_string);
return result;
}
catch (Exception ex)
{
throw ex;
}
finally
{
DbAcess = null;
}
Database layer code is as follows
public int Insert_Query(string strSQL)
{
SqlConnection con = new SqlConnection();
con = OpenConnection();
try
{
sqlcmd = new SqlCommand();
sqlcmd.Connection = con;
sqlcmd.CommandType = CommandType.StoredProcedure;
sqlcmd.CommandText = strSQL;
int Result = sqlcmd.ExecuteNonQuery();
return Result;
}
catch (Exception ex)
{
throw ex;
}
finally
{
con.Close();
}
}
Instead of passing strSQL as the CommandText, where strSQL is the string you create in the first code block (I think...), just pass the SP name as the CommandText and then add Parameters to your sqlcmd object.
SqlParameter p = new SqlParameter("#ParameterName", parametervalue));
sqlcmd.Parameters.Add(p);
Just to try to RESOLVE your problem, but BEWARE that this method is very dangerous and NOT RECOMMENDED for the Sql Injection problem.
string Query_string = "EXEC SP_InsertOffer_Tab #offer_name ='" +
this.offer_name +"', #offer_price = " +
this.offer_price + ",#start_date = '" +
this.start_date + "',#end_date = '" + this.end_date + "'";
and change the CommandType to Text.
A better approach would be to change the Insert_Query method
public int Insert_Query(string strSQL, SqlParameter[] prm)
{
using(SqlConnection con = OpenConnection())
{
sqlcmd = new SqlCommand(strSql, con);
sqlcmd.CommandType = CommandType.StoredProcedure;
sqlcmd.Parameters.AddRange(prm)
int Result = sqlcmd.ExecuteNonQuery();
return Result;
}
}
then call it in this way
SqlParameter[] prms = new SqlParameter[]
{
new SqlParameter("#offer_name", SqlDbType.NVarChar),
new SqlParameter("#offer_price", SqlDbType.Money),
new SqlParameter("#start_date", SqlDbType.SmallDateTime),
new SqlParameter("#end_date", SqlDbType.SmallDateTime)
};
prms[0].Value = this.offer_name;
prms[1].Value = this.offer_price;
prms[2].Value = this.start_date;
prms[3].Value = this.end_date;
int result = DbAcess.Insert_Query(Query_string, prms);