I'm attempting to do 2 SQL inserts consecutively to 2 different tables.
The first table insert works fine. It uses SELECT SCOPE_IDENTITY() to pull the index number which I then store in the variable Registree_Index. This works OK.
I then try to insert Registree_Index and some other variables into a second table. This does not write to the second table at all. No error message either.
Initially I thought the error had something to do with reusing my old query and connection string variables, so I created new ones. This has not helped.
Does anyone have thoughts on this? Code follows...
private void WriteToDatabase()
{
Guid newGuid = Guid.NewGuid();
string yearstring = DateTime.Now.Year.ToString();
string twodigityear = yearstring.Substring(yearstring.Length-2);
string dateAndGuid = twodigityear + "-" + DateTime.Now.Month.ToString() + "-" + DateTime.Now.Day.ToString() + "-" + DateTime.Now.Hour.ToString() + "-" + DateTime.Now.Minute.ToString() + "-" + DateTime.Now.Second.ToString() + "-" + newGuid;
string connectionString = GetConnectionString();
SqlConnection connection = new SqlConnection();
connection.ConnectionString = connectionString;
connection.Open();
string insertQuery = "INSERT INTO registrees (UIDindex, Submission_Number, Homecoming_Form, HC_form, NewRecord, First_Name, Last_Name, Billing_Phone, Addresses_Same, Email) VALUES (#UIDindex, #Submission_Number, #Homecoming_Form, #HC_form, #NewRecord, #First_Name, #Last_Name, #Billing_Phone, #Addresses_Same, #Email) SELECT SCOPE_IDENTITY()";
SqlCommand cmd = new SqlCommand(insertQuery, connection);
cmd.Parameters.AddWithValue("#UIDindex", dateAndGuid);
cmd.Parameters.AddWithValue("#Submission_Number", 1);
cmd.Parameters.AddWithValue("#Homecoming_Form", 1);
cmd.Parameters.AddWithValue("#HC_form", "platform");
cmd.Parameters.AddWithValue("#NewRecord", 1);
cmd.Parameters.AddWithValue("#First_Name", First_Name.Text);
cmd.Parameters.AddWithValue("#Last_Name", Last_Name.Text);
cmd.Parameters.AddWithValue("#Billing_Phone", Phone.Text);
cmd.Parameters.AddWithValue("#Addresses_Same", 1);
cmd.Parameters.AddWithValue("#Email", Email.Text);
///get index from scope identity
int Registree_Index = Convert.ToInt32(cmd.ExecuteScalar());
///SO FAR EVERYTHING WORKS GREAT! BUT THE REST OF THIS CODE FAILS SOMEHOW.
connection.Close();
connection = null;
insertQuery = null;
cmd = null;
string connectionString2 = GetConnectionString();
SqlConnection connection2 = new SqlConnection();
connection2.ConnectionString = connectionString2;
connection2.Open();
string insertQuery2 = "INSERT INTO event_registration (Registree_Index, UIDindex, Submission_Number) VALUES (#Registree_Index, #UIDindex, #Submission_Number)";
SqlCommand cmd2 = new SqlCommand(insertQuery2, connection2);
cmd2.Parameters.AddWithValue("#Registree_Index", Registree_Index);
cmd2.Parameters.AddWithValue("#UIDindex", dateAndGuid);
cmd2.Parameters.AddWithValue("#Submission_Number", 1);
}
I don't see anywhere you are calling cmd2.ExecuteScalar()
How about this...
private void WriteToDatabase()
{
Guid newGuid = Guid.NewGuid();
string yearstring = DateTime.Now.Year.ToString();
string twodigityear = yearstring.Substring(yearstring.Length - 2);
string dateAndGuid = twodigityear + "-" + DateTime.Now.Month.ToString() + "-" + DateTime.Now.Day.ToString() + "-" + DateTime.Now.Hour.ToString() + "-" + DateTime.Now.Minute.ToString() + "-" + DateTime.Now.Second.ToString() + "-" + newGuid;
int Registree_Index;
using (SqlConnection connection = new SqlConnection(GetConnectionString()))
{
connection.Open();
string insertQuery = "INSERT INTO registrees (UIDindex, Submission_Number, Homecoming_Form, HC_form, NewRecord, First_Name, Last_Name, Billing_Phone, Addresses_Same, Email) VALUES (#UIDindex, #Submission_Number, #Homecoming_Form, #HC_form, #NewRecord, #First_Name, #Last_Name, #Billing_Phone, #Addresses_Same, #Email) SELECT SCOPE_IDENTITY()";
using (SqlCommand cmd = new SqlCommand(insertQuery, connection))
{
cmd.Parameters.AddWithValue("#UIDindex", dateAndGuid);
cmd.Parameters.AddWithValue("#Submission_Number", 1);
cmd.Parameters.AddWithValue("#Homecoming_Form", 1);
cmd.Parameters.AddWithValue("#HC_form", "platform");
cmd.Parameters.AddWithValue("#NewRecord", 1);
cmd.Parameters.AddWithValue("#First_Name", First_Name.Text);
cmd.Parameters.AddWithValue("#Last_Name", Last_Name.Text);
cmd.Parameters.AddWithValue("#Billing_Phone", Phone.Text);
cmd.Parameters.AddWithValue("#Addresses_Same", 1);
cmd.Parameters.AddWithValue("#Email", Email.Text);
///get index from scope identity
Registree_Index = Convert.ToInt32(cmd.ExecuteScalar());
}
string insertQuery2 = "INSERT INTO event_registration (Registree_Index, UIDindex, Submission_Number) VALUES (#Registree_Index, #UIDindex, #Submission_Number)";
using (SqlCommand cmd = new SqlCommand(insertQuery2, connection))
{
cmd.Parameters.AddWithValue("#Registree_Index", Registree_Index);
cmd.Parameters.AddWithValue("#UIDindex", dateAndGuid);
cmd.Parameters.AddWithValue("#Submission_Number", 1);
cmd.ExecuteNonQuery();
}
}
}
That's because you never execute cmd2. Since insertQuery2 is only inserting to event_registration table, you can execute cmd2 by calling cmd2.ExecuteNonQuery().
On a side note, you should consider to use using statement to make sure that connection and connection2 are closed after the queries are executed. Below is the modified code with using statement
private void WriteToDatabase()
{
Guid newGuid = Guid.NewGuid();
string yearstring = DateTime.Now.Year.ToString();
string twodigityear = yearstring.Substring(yearstring.Length-2);
string dateAndGuid = twodigityear + "-" + DateTime.Now.Month.ToString() + "-" + DateTime.Now.Day.ToString() + "-" + DateTime.Now.Hour.ToString() + "-" + DateTime.Now.Minute.ToString() + "-" + DateTime.Now.Second.ToString() + "-" + newGuid;
string connectionString = GetConnectionString();
string insertQuery = "INSERT INTO registrees (UIDindex, Submission_Number, Homecoming_Form, HC_form, NewRecord, First_Name, Last_Name, Billing_Phone, Addresses_Same, Email) VALUES (#UIDindex, #Submission_Number, #Homecoming_Form, #HC_form, #NewRecord, #First_Name, #Last_Name, #Billing_Phone, #Addresses_Same, #Email) SELECT SCOPE_IDENTITY()";
int Registree_Index = 0;
using (SqlConnection connection = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand(insertQuery, connection))
{
cmd.Parameters.AddWithValue("#UIDindex", dateAndGuid);
cmd.Parameters.AddWithValue("#Submission_Number", 1);
cmd.Parameters.AddWithValue("#Homecoming_Form", 1);
cmd.Parameters.AddWithValue("#HC_form", "platform");
cmd.Parameters.AddWithValue("#NewRecord", 1);
cmd.Parameters.AddWithValue("#First_Name", First_Name.Text);
cmd.Parameters.AddWithValue("#Last_Name", Last_Name.Text);
cmd.Parameters.AddWithValue("#Billing_Phone", Phone.Text);
cmd.Parameters.AddWithValue("#Addresses_Same", 1);
cmd.Parameters.AddWithValue("#Email", Email.Text);
connection.Open();
///get index from scope identity
Registree_Index = Convert.ToInt32(cmd.ExecuteScalar());
}
}
string connectionString2 = GetConnectionString();
string insertQuery2 = "INSERT INTO event_registration (Registree_Index, UIDindex, Submission_Number) VALUES (#Registree_Index, #UIDindex, #Submission_Number)";
using (SqlConnection connection2 = new SqlConnection(connectionString2))
{
using (SqlCommand cmd2 = new SqlCommand(insertQuery2, connection2))
{
cmd2.Parameters.AddWithValue("#Registree_Index", Registree_Index);
cmd2.Parameters.AddWithValue("#UIDindex", dateAndGuid);
cmd2.Parameters.AddWithValue("#Submission_Number", 1);
connection2.Open();
cmd2.ExecuteNonQuery();
}
}
}
Related
i create small project that read data from sqlserver then insert into mysql table.
i want to users write SQL and mysql command into textbox.
here is my problem, when i run project the field that inserted into mysql table are: myReader["STableName"].ToString()
like this picture:
connections are fine, here is my code:
string address;
string username;
string password;
string database;
address = textBox1.Text;
username = textBox2.Text;
password = textBox3.Text;
database = textBox4.Text;
//MySql
string mysqladdress;
string mysqlusername;
string mysqlpassword;
string mysqldatabase;
mysqladdress = textBox7.Text;
mysqlusername = textBox8.Text;
mysqlpassword = textBox9.Text;
mysqldatabase = textBox10.Text;
//SQLCode
string sqlcmnd1;
string sqlcmnd2;
sqlcmnd1 = textBox5.Text;
sqlcmnd2 = textBox6.Text;
SqlConnection conn = new SqlConnection();
conn.ConnectionString =
"Data Source=" + address + ";" +
"Initial Catalog=" + database + ";" +
"User id=" + username + ";" +
"Password=" + password + ";";
try
{
conn.Open();
SqlDataReader myReader = null;
SqlCommand myCommand = new SqlCommand(sqlcmnd1, conn);
myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
string connectionString = #"server=" + mysqladdress + ";" + "username=" + mysqlusername + ";" + "password=" + mysqlpassword + ";" + "database=" + mysqldatabase + "";
MySqlConnection connection = null;
MySqlDataReader reader = null;
try
{
connection = new MySqlConnection(connectionString);
connection.Open();
string stm = sqlcmnd2;//here is my problem
MySqlDataAdapter dataAdapter = new MySqlDataAdapter();
dataAdapter.SelectCommand = new MySqlCommand(stm, connection);
DataTable table = new DataTable();
dataAdapter.Fill(table);
}
sqlcmnd2:
INSERT INTO test (CusCode,STableName,Date,ModdatZaman) VALUES ('" + myReader["CusCode"].ToString() + "','" + myReader["STableName"].ToString() + "','" + myReader["Date"].ToString() + "','" + myReader["ModdatZaman"].ToString() + "')
sqlcmnd1:
SELECT * FROM __TempUserCompRep__
Text from a textbox is considered as a full string it not replace the actual value of the variable .
You need to use prepared statement for that.
In textbox6 you write the command like this :
INSERT INTO test (CusCode,STableName,Date,ModdatZaman) VALUES (#CusCode,#STableName,#Date,#ModdatZaman)
After that in code, bind the parameter with variable from you actually want to take value.
For example:
MySqlConnection con = null;
try
{
string myConnectionString = "server=localhost;database=test;uid=root;pwd=root;";
con = new MySqlConnection(myConnectionString);
string CmdString = textBox6.Text.ToString();
MySqlCommand cmd = new MySqlCommand(CmdString, con);
cmd.Parameters.Add("#CusCode", MySqlDbType.VarChar, 50);
cmd.Parameters.Add("#STableName", MySqlDbType.VarChar, 50);
cmd.Parameters.Add("#Date", MySqlDbType.VarChar, 50);
cmd.Parameters.Add("#ModdatZaman", MySqlDbType.VarChar, 50);
cmd.Parameters["#CusCode"].Value = myReader["CusCode"].ToString();
cmd.Parameters["#STableName"].Value = myReader["STableName"].ToString();
cmd.Parameters["#Date"].Value = myReader["Date"].ToString();
cmd.Parameters["#ModdatZaman"].Value = myReader["ModdatZaman"].ToString();
con.Open();
int RowsAffected = cmd.ExecuteNonQuery();
if (RowsAffected > 0)
{
MessageBox.Show("Insert Query sucessfully!");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
if (con != null && con.State == ConnectionState.Open)
{
con.Close();
}
}
Note: I consider all four columns are varchar type in the database. you modify it according to your requirement
Hello Muhammad i would suggest you not to execute the sql commands from text box as there is a high chance of sql injection attacks , try to avoid as much you can , its a suggestion for more secured application
Error image is here
the error is in query line , its shows syntax error
try
{
string zero = "0";
DateTime dat = this.dateTimePicker1.Value.Date;
connection1.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection1;
command.CommandText = "insert into client_table(CLIENT, DATE,BILL_AMOUNT, PAID_AMOUNT, BALANCE, CONTACT, ADDRESS )VALUES ('" + txt_client.Text + "', #" + dat.ToLongDateString() + "# ,'" + zero + "','" + zero + "','" + zero + "','" + txt_contact.Text + "','" + txt_address.Text + "')";
command.ExecuteNonQuery();
connection1.Close();
MessageBox.Show("New Client Registration done Successfully.");
connection1.Dispose();
this.Hide();
employee_form f1 = new employee_form("");
f1.ShowDialog();
}
thank you in advance
In Access, dates are delimited by #, not '. Also, Access does not recognize the long date format. But dates are not stored in any format so no worries, change it to:
... + "', #" + dat.ToString() + "# ...etc.
Although if you do not parameterize your query serious damage or data exposure can be done through SQL Injection because someone could type in a SQL statement into one of those textboxes that you are implicitly trusting.
Working example:
class Program
{
static void Main(string[] args)
{
System.Data.OleDb.OleDbConnectionStringBuilder bldr = new System.Data.OleDb.OleDbConnectionStringBuilder();
bldr.DataSource = #"C:\Users\tekhe\Documents\Database2.mdb";
bldr.Provider = "Microsoft.Jet.OLEDB.4.0";
using (System.Data.OleDb.OleDbConnection cnxn = new System.Data.OleDb.OleDbConnection(bldr.ConnectionString))
{
cnxn.Open();
Console.WriteLine("open");
using (System.Data.OleDb.OleDbCommand cmd = new System.Data.OleDb.OleDbCommand())
{
cmd.Connection = cnxn;
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = "INSERT INTO [Table1] ([Dob]) VALUES(#" + DateTime.Now.ToString() + "#)";
cmd.ExecuteNonQuery();
}
}
Console.ReadKey();
}
}
Update
However, you want to do something more like this which uses Parameters to protect against SQL Injection which is extremely easy to exploit so do not think that you don't really need to worry about it:
static void Main(string[] args)
{
OleDbConnectionStringBuilder bldr = new OleDbConnectionStringBuilder();
bldr.DataSource = #"C:\Users\tekhe\Documents\Database2.mdb";
bldr.Provider = "Microsoft.Jet.OLEDB.4.0";
using (System.Data.OleDb.OleDbConnection cnxn = new OleDbConnection(bldr.ConnectionString))
{
cnxn.Open();
Console.WriteLine("open");
using (System.Data.OleDb.OleDbCommand cmd = new OleDbCommand())
{
cmd.Connection = cnxn;
cmd.CommandType = System.Data.CommandType.Text;
OleDbParameter dobParam = new OleDbParameter("#dob", OleDbType.Date);
dobParam.Value = DateTime.Now;
cmd.Parameters.Add(dobParam);
cmd.CommandText = "INSERT INTO [Table1] ([Dob]) VALUES(#dob)";
cmd.ExecuteNonQuery();
}
}
Console.ReadKey();
}
//code to write date in the access table.
string zero = "0";
DateTime dat = this.dateTimePicker1.Value.Date;
//MessageBox.Show(dat.ToShortDateString());
connection1.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection1;
//command.CommandText = "insert into client_table(DATEE) values( '"dat.ToShortDateString()+"')";
command.CommandText = "insert into client_table (CLIENT, DATEE, BILL_AMOUNT, PAID_AMOUNT, BALANCE, CONTACT, ADDRESS )VALUES ('" + txt_client.Text + "', #"+dat.ToShortDateString()+"# ,'" + zero + "','" + zero + "','" + zero + "','" + txt_contact.Text + "','" + txt_address.Text + "')";
command.ExecuteNonQuery();
connection1.Close();
MessageBox.Show("New Client Registration done Successfully.");
connection1.Dispose();
//New code for receiving the date between two range of dates
try
{
DateTime dat = this.dateTimePicker1.Value.Date;
DateTime dat2 = this.dateTimePicker2.Value.Date;
// MessageBox.Show(dat.ToShortDateString() + " " + dat2.ToShortDateString());
connection1.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection1;
string query;
query = "select * from client_table Where DATEE Between #" + dat.ToLongDateString() +"# and #" + dat2.ToLongDateString() + "# ";
command.CommandText = query;
OleDbDataAdapter da = new OleDbDataAdapter(command);
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
connection1.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error" + ex);
}
Thank you all of you for the support.
public void create(account_detail c, int jobcard_id)
{
SqlConnection con = new SqlConnection(#"Data source =(LocalDB)\v11.0;AttachDbFilename=C:\Users\Wattabyte Inc\Documents\CarInfo.mdf;Integrated Security=True;");
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
con.Open();
string additionalText = string.Empty;
bool needComma = false;
foreach (var details in c.Data)
{
if (needComma)
{
additionalText += ", ";
}
else
{
needComma = true;
additionalText += "('" + jobcard_id + "','" + details.completed_by + "','" + details.reporting_time + "','" + details.cost_activity + "','" + details.spared_part_used + "')";
}
cmd.CommandText = "insert into child_detail values " + additionalText + ";";
cmd.ExecuteNonQuery();
}
I am using this code but it only taking single value but I want to save multiple values into the database. How can I achieve this?
If you need multiple jobcard_id then do this.
Note this is making it fit in your code, I suggest you do some refactoring and figure out a better way to do this because it's just plain ugly.
public void create(account_detail c, List<int> jobcard_ids)
{
SqlConnection con = new SqlConnection(#"Data source =(LocalDB)\v11.0;AttachDbFilename=C:\Users\Wattabyte Inc\Documents\CarInfo.mdf;Integrated Security=True;");
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
con.Open();
string additionalText = string.Empty;
bool needComma = false;
foreach (var details in c.Data)
{
if (needComma)
{
additionalText += ", ";
}
else
{
needComma = true;
foreach(var jobcard_id in jobcard_ids)
{
additionalText += "('" + jobcard_id + "','" + details.completed_by + "','" + details.reporting_time + "','" + details.cost_activity + "','" + details.spared_part_used + "')";
if (jobcard_id != jobcard_ids.Last())
{
// We will need to comma separate the query string unless it's the last item
additionalText+= ",";
}
}
}
cmd.CommandText = "insert into child_detail values " + additionalText + ";";
cmd.ExecuteNonQuery();
}
//How to exceute multiple sqlcommands in one transaction in C#..i am using like this but it gives me error..plz let me know what is problem with code..
string[] files = Directory.GetFiles(dir);
foreach (string subfiles in files)
{
con.Open();
SqlTransaction myTrans=null;
myTrans= con.BeginTransaction();
try
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.Transaction = myTrans;
cmd.CommandText = "select descr from genlookup where Code='SS_Purchase_No' and RecId=99998";
SqlDataReader drr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
DataTable dt = new DataTable();
//SqlDataAdapter da = new SqlDataAdapter(qry1, con);
DataTable dtw = new DataTable();
dtw.Load(drr);
DataSet dsr = new DataSet();
dsr.Tables.Add(dtw);
//SqlDataAdapter darun = new SqlDataAdapter("select descr from genlookup where Code='SS_Purchase_No' and RecId=99998", con);
//DataSet dsr = new DataSet();
//darun.Fill(dsr);
int run_no = Convert.ToInt32(dsr.Tables[0].Rows[0]["descr"].ToString());
filename = Path.GetFileNameWithoutExtension(subfiles);
string filenames = Path.GetFileName(subfiles);
if (subfiles.Trim().EndsWith(".xlsx"))
{
strConn = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0 Xml;HDR=YES;IMEX=1\";", subfiles);
}
else if (subfiles.Trim().EndsWith(".xls"))
{
strConn = string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1\";", subfiles);
}
OleDbConnection exlcon = new OleDbConnection(strConn);
exlcon.Open();
string myTableName = exlcon.GetSchema("Tables").Rows[0]["TABLE_NAME"].ToString();
OleDbDataAdapter oledbadpt = new OleDbDataAdapter(String.Format("SELECT * FROM [{0}] ", myTableName), exlcon);
DataSet d_s = new DataSet();
oledbadpt.Fill(d_s);
exlcon.Close();
for (int i = 7; i < d_s.Tables[0].Rows.Count - 1; i++)
{
PARTNER_ID = d_s.Tables[0].Rows[i]["F1"].ToString();
RTV_LOCTN = d_s.Tables[0].Rows[i]["F3"].ToString();
DateTime date1 = Convert.ToDateTime(d_s.Tables[0].Rows[i]["F13"]);
string ddmm = date1.ToString("yyyyMMdd");
string[] aa = Color_size.Split('/');
// string colr="";
string size = "";
foreach (string ss in aa)
{
size = ss;
}
}
con.Open();
SqlCommand myCommand = new SqlCommand();
myCommand.Connection = con;
myCommand.Transaction = myTrans;
myCommand.CommandText = "insert into HSR_Purch_RETURN(PARTNER_ID,RTV_LOCTN)" +
" values('" + PARTNER_ID + "'," + "'" + RTV_LOCTN + "') ";
myCommand.ExecuteNonQuery();
//con.Open();
//SqlCommand cmdd = new SqlCommand(insert, con);
//int value1 = cmdd.ExecuteNonQuery();
//values = string.Empty;
con.Close();
if ((shrwcode != "") && (flag == "F"))
{
string zz = "select DistributionCenter,GLCountry,GLZone,GLState,GLCity from showroommaster where ShowroomCode='" + shrwcode + "'";
SqlDataAdapter da11 = new SqlDataAdapter(zz, con);
DataSet ds11 = new DataSet();
da11.Fill(ds11);
string Dcenter = ds11.Tables[0].Rows[0]["DistributionCenter"].ToString();
string GLCountry = ds11.Tables[0].Rows[0]["GLCountry"].ToString();
string fff = "select isnull(max(EntSrlNo),0)+1 as EntSrlNo from IDTableExtd where ShowroomCode='" + shrwcode + "' and DocDate='" + RTV_DATE + "'";
SqlDataAdapter das = new SqlDataAdapter(fff, con);
DataSet dss = new DataSet();
das.Fill(dss);
SqlCommand extdcmd = new SqlCommand();
extdcmd.Connection = con;
extdcmd.Transaction = myTrans;
string docpre = "PR" + RTV_DATE.Substring(2, 2);
if (dss.Tables[0].Rows.Count > 0)
{
slno = Convert.ToInt32(dss.Tables[0].Rows[0]["EntSrlNo"].ToString());
extdcmd.CommandText = "insert into IDTableExtd (ShowroomCode,TrnType,TrnCtrlNo,DocNoPrefix,docno,DocDate,EntSrlNo,StockNo,DistributionCenter,GLCountry,GLZone,GLState,GLCity,PartyType,PromoValue_LineLevel,DocQty,NetValue,BatchSrlNo)" +
"values ('" + shrwcode + "'," + "'2300'," + "'" + ddmm + "'," + "'" + docpre + "'," + "'" + ddmm + "'," + "'" + RTV_DATE + "'," + "'" + slno + "'," + "'" + TRN_STOCKNO + "'," + "'" + Dcenter + "'," + "'" + GLCountry + "'," + "'" + GLZone + "',"
+ "'" + GLState + "'," + "'" + GLCity + "','10'," + '0' + ",'" + RTV_QTY + "'," + "'" + RTV_cost + "','0')";
con.Open();
// SqlCommand extdcmd = new SqlCommand(instableextd, con);
extdcmd.ExecuteNonQuery();
con.Close();
}
}
}
myTrans.Commit(); ///Error is getting after exceuting this line..
You need refactor your´s code, first, and use something like that:
using (var = new SqlConnection(_connectionstring))
{
try
{
connection.Open();
using(SqlTransaction transaction = connection.BeginTransaction())
{
using (SqlCommand command1= new SqlCommand(commandtext, connection, transaction ))
{
//Do something here
}
using (SqlCommand command2= new SqlCommand(commandtext, connection, transaction ))
{
//Do another stuff here
}
...
transaction .Commit();
}
}
catch (Exception Ex)
{
if (transaction != null) transaction .Rollback();
}
}
(1)As Joseph said refactor your code using Using statement, which helps to dispose the objects properly.
(2)Your code is prone to SQL Injection, so use SQLParameter.
I've shown a sample from your code make it fully.
con.Open();
SqlCommand myCommand = new SqlCommand();
myCommand.Connection = con;
myCommand.Transaction = myTrans;
myCommand.CommandText = "insert into HSR_Purch_RETURN(PARTNER_ID,RTV_LOCTN) values(#partnerId,#rtv)";
myCommand.Parameters.Add(new SqlParameter("partnerId",PARTNER_ID));
myCommand.Parameters.Add(new SqlParameter("rtv",RTV_LOCTN));
myCommand.ExecuteNonQuery();
//con.Open();
//SqlCommand cmdd = new SqlCommand(insert, con);
//int value1 = cmdd.ExecuteNonQuery();
//values = string.Empty;
con.Close();
I'm trying to make a search button that when i enter an ID to a Textbox and press it , it goes to my private SQL server database and get the data row referred to that ID , But The exception handler brings me error because of my wrong CommandText .. Here is my Code
private void SearchBtn_Click(object sender, EventArgs e)
{
cn.ConnectionString = Properties.Settings.Default.ConStr;
if (ID.Text == "")
{
MessageBox.Show("Please Enter The ID you would like to search");
}
else
{
SqlCommand com = new SqlCommand();
cn.Open();
SqlParameter user = new SqlParameter("#ID", SqlDbType.Int);
SqlParameter FN = new SqlParameter("#First_Name",SqlDbType.NChar);
SqlParameter LN = new SqlParameter("#Last_Name", SqlDbType.VarChar);
SqlParameter Jb = new SqlParameter("#Job", SqlDbType.VarChar);
SqlParameter Ag = new SqlParameter("#Age", SqlDbType.VarChar);
SqlParameter ph = new SqlParameter("#Phone", SqlDbType.VarChar);
com.Parameters.Add(user);
com.Parameters.Add(FN);
com.Parameters.Add(LN);
com.Parameters.Add(Jb);
com.Parameters.Add(Ag);
com.Parameters.Add(ph);
com.Connection = cn;
Here is my Error :
*com.CommandText = "Search (First_Name,Last_Name,Job,Age,Phone) values('" + FN + "','" + LN + "','" + Jb+ "','" + Ag + "','" + ph + "' from MyList) ";*
user.Direction = ParameterDirection.Input;
FN.Direction = ParameterDirection.Output;
LN.Direction = ParameterDirection.Output;
Jb.Direction = ParameterDirection.Output;
Ag.Direction = ParameterDirection.Output;
ph.Direction = ParameterDirection.Output;
FN.Size = 10;
LN.Size = 10;
Jb.Size = 10;
Ag.Size = 10;
ph.Size = 10;
user.Value = Convert.ToInt32(ID.Text);
try
{
com.ExecuteNonQuery();
FirstName.Text = FN.Value.ToString();
LastName.Text = LN.Value.ToString();
Job.Text = Jb.Value.ToString();
Age.Text = Ag.Value.ToString();
Phone.Text = ph.Value.ToString();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
cn.Close();
}
I'm Using Visual Studio 2012 .
Thanks in Advance .
"Search (First_Name,Last_Name,Job,Age,Phone) values('" + FN + "','" + LN + "','" + Jb+ "','" + Ag + "','" + ph + "' from MyList)"
doesn't really look like SQL. Also I'm not quite sure why you're setting loads of parameters you're not using.
Maybe you meant something like
com.CommandText = "SELECT First_Name, Last_Name, Job, Age, Phone FROM MyList WHERE ID=#Id";
com.Parameters.AddWithValue("#Id", ID.Text);
Furthermore if that's your intention, then ExecuteNonQuery is wrong as that's for INSERT, UPDATE and other things that don't return a result.
Command text should be like
com.CommandText = "SELECT First_Name, Last_Name, Job, Age, Phone FROM MyList WHERE ....";
Remove most of your parameters, leave only input ones.
Instead of com.ExecuteNonQuery() use: SqlDataReader reader = command.ExecuteReader(); and using it read your data. Example article is here
Firstly:
"Search (First_Name,Last_Name,Job,Age,Phone) values('" + FN + "','" + LN + "','" + Jb+ "','" + Ag + "','" + ph + "' from MyList)"
Doesn't look like valid SQL to me.
I think you're looking to do something like this:
using (SqlConnection myConnection = new SqlConnection(connString))
{
string oString = " SELECT * from MyList WHERE (id = #id)";
SqlCommand oCmd = new SqlCommand(oString, myConnection);
oCmd.Parameters.Add(new SqlParameter("#id", ID.Text));
myConnection.Open();
string name="";
string lastname ="";
using (SqlDataReader oReader = oCmd.ExecuteReader())
{
while (oReader.Read())
{
name = oReader["name"].ToString(); // replace "name" with the name of the column you want
lastname = oReader["lastname"].ToString();
}
}
myConnection.Close();
return name + lastname;
You can use these values to set the text in your textboxes on your form:
YourNameTextbox.Text = name;
.. etc