get a parameter from database with query c# - c#

string s = "select idviagem from tbviagem where dia like '" + idatxt.Text + "'";
cmd = new SqlCommand(s, con);
I need the idviagem from the table tbviagem to put in idviagem from tbpassageiro (it's FK on tbpassageiro) , but i need the get idviagem from idatxt.Text it's a DateTime format, but doing the insert (look down) gives me the error:
Conversion failed when converting the nvarchar value 'select idviagem from tbviagem where dia like '06/12/2018 00:00:00'' to data type int.'
but idviagem is a int, of course .
string q = "insert into tbpassageiro (nome,cc,fotocc,idviagem) values(#n,#cc,#p,#iv)";
cmd = new SqlCommand(q, con);
con.Open();
cmd.Parameters.AddWithValue("#p", data);
cmd.Parameters.AddWithValue("#n", nometxt.Text);
cmd.Parameters.AddWithValue("#cc", cctxt.Text);
cmd.Parameters.AddWithValue("#iv", s);
cmd.ExecuteNonQuery();

You should never execute SQL statements like that but use parameters. You are using parameters for your second statement but not doing it for the first one.
Having said that, you are trying to use the query string s as the parameter value for #iv. Instead you should ExecuteScalar in first and use the result of it in second.
However, you can both get the idviagem value and do the insert in one single statement like this:
string q = #"insert into tbpassageiro
(nome,cc,fotocc,idviagem)
select #n,#cc,#p,idViagem from tbviagem where dia like #dia";
SqlCommand cmd = new SqlCommand(q, con);
cmd.Parameters.AddWithValue("#p", data);
cmd.Parameters.AddWithValue("#n", nometxt.Text);
cmd.Parameters.AddWithValue("#cc", cctxt.Text);
cmd.Parameters.Add("#dia", SqlDbType.VarChar).Value = idatxt.Text;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Note: I don't suggest using AddWithValue, prefer Add instead.
EDIT: For sampling with a Datetime dia field:
DateTime dt;
cmd.Parameters.Add("#dia", SqlDbType.DateTime);
if (DateTime.TryParse(idatxt.Text, out dt))
{
cmd.Parameters["#dia"].Value = dt;
}
else
{
cmd.Parameters["#dia"].Value = DBNull.Value;
}
If idatxt is for getting a date\datetime value it would be much easier to use DateTimePicker to get a valid DateTime value.

It looks like you are passing the query string s as the parameter value for #iv instead of the result of that query.
I suggest executing your command cmd and passing the result value to #iv:
string s = "select idviagem from tbviagem where dia like '" + idatxt.Text + "'";
cmd = new SqlCommand(s, con);
con.Open();
Int32 resultValue = (Int32) cmd.ExecuteScalar();
string q = "insert into tbpassageiro (nome,cc,fotocc,idviagem) values(#n,#cc,#p,#iv)";
cmd = new SqlCommand(q, con);
cmd.Parameters.AddWithValue("#p", data);
cmd.Parameters.AddWithValue("#n", nometxt.Text);
cmd.Parameters.AddWithValue("#cc", cctxt.Text);
cmd.Parameters.AddWithValue("#iv", resultValue);
cmd.ExecuteNonQuery();

Related

Passing parameter in select statement in postgresql

I am trying to pass parameter for below select statement in postgresql, but it is not returning any row,
cmd.Parameters.AddWithValue("#name", richTextBox_searchEmp.Text);
string sql = "select * from tbl_emp_Info where LOWER(firstname) like LOWER('#name%');";
where- richTextBox_searchEmp.Text is “first”
have also tried -
cmd.Parameters.AddWithValue("#name", NpgsqlDbType.Char , searchEmp.Text);
while, parameter less query below always returning correct results.
string sql = "select * from tbl_emp_Info where LOWER(firstname) like LOWER('first%');";
Please help!!!
Complete Code-
conn.Open();
cmd.Parameters.AddWithValue("#name", NpgsqlDbType.Char , richTextBox_searchEmp.Text);
string sql = "select * from tbl_emp_Info where LOWER(firstname) like LOWER('#name%');";
NpgsqlDataAdapter da = new NpgsqlDataAdapter(sql, conn);
cmd.Connection = conn;
cmd.CommandText = sql;
cmd.ExecuteNonQuery();
ds.Reset();
da.Fill(ds);
dt = ds.Tables[0];
dataGridView.DataSource = dt;
Pass your parameter with % like
Change you query to
string sql = "select * from tbl_emp_Info where LOWER(firstname) like LOWER(#name);";
And Pass #name like
cmd.Parameters.AddWithValue("#name", "%" + searchEmp.Text + "%");

Weird error in "insert into" command?

I know this may sound rubbish but that's the truth.
everytime when i try to run this code i get syntax error.
any idea why?
OleDbConnection con = new OleDbConnection();
con.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Rock.accdb";
con.Open();
String query = "insert into category ([name],desc) values (#1,#2)";
OleDbCommand cmd = new OleDbCommand(query, con);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#1", textBox1.Text);
cmd.Parameters.AddWithValue("#2", textBox2.Text);
cmd.ExecuteNonQuery();
textBox1.Text = null;
textBox2.Text = null;
label4.Text = "New Category Created";
label4.ForeColor = Color.Green;
the error is: Syntax error in INSERT INTO statement # cmd.ExecuteNonQuery();
desc is also a keyword (for descending) and so you'd need:
String query = "insert into category ([name],[desc]) values (#1,#2)";
Change your insert query like this,
String query = "insert into category ([name], [desc]) values (#1,#2)";
desc is reserved word by default. Also, please close your connection by con.Close(); after executing the command.

"Error converting data type nvarchar to numeric."

I want to Insert record to the database with a ComboBox. The ComboBox is connected to the other table and this is the error:
Error converting data type nvarchar to numeric.
private void InsertReceipt()
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = cn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "INSERT INTO Ticket(CustomerID, Date, Store, Amount, NoStub)" +
"VALUES (#CustomerID, #Date, #Store, #Amount, #NoStub) ";
cmd.Parameters.AddWithValue("#CustomerID", cboName.SelectedValue);
cmd.Parameters.AddWithValue("#Date", dtpDate.Value.Date.ToString());
cmd.Parameters.AddWithValue("#Store", txtStore.Text);
cmd.Parameters.AddWithValue("#Amount", txtAmount.Text);
cmd.Parameters.AddWithValue("#NoStub", txtStub.Text);
cmd.ExecuteNonQuery();
}
void GetRecords2()
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = cn;
cmd.CommandText = "SELECT CustomerID, firstname + ', ' + lastname AS Name FROM Customer";
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adp.Fill(ds, "Customer");
cboName.DataSource = ds;
cboName.DisplayMember = "Customer.Name";
cboName.ValueMember = "Customer.CustomerID";
}
When you call AddWithValue make sure that the type of data you are passing matches the column type. Here's a likely candidate:
cmd.Parameters.AddWithValue("#Amount", txtAmount.Text);
In this line you are passing a text string to something that clearly wants a numeric value (an amount). You should parse the txtAmount.Text into a decimal first and then pass that value:
decimal amount = decimal.Parse(txtAmount.Text);
cmd.Parameters.AddWithValue("#Amount", amount);
With this code, you may still get an exception if the string in txtAmount.Text can't be parsed into a decimal, but at least then you'll know which value is causing the problem. You can/should do the same with the other values as well to make sure they match their column types.
try string.isNullorEmpty(txtAmount.text);
private void button1_Click(object sender, EventArgs e)
{
string sql;
sql = "insert into slab (date,sober_visor,tesh,shift,group,heat_no,st_grade,thick,width,length,location,pcs,remarkes,slab_no) values (#date,#sober_vsor,#tesh,#shift,#group,#heat_no,#st_grade,#thick,#width,#length,#loction,#pcs,#slab_no);select scope_identity()";
SqlCommand cmd = new SqlCommand(sql, con);
cmd.Parameters.AddWithValue("#date", txt_date.Text);
cmd.Parameters.AddWithValue("#sober_visor", com_sober_visor.ToString());
cmd.Parameters.AddWithValue("#shift", txt_shift.Text);
cmd.Parameters.AddWithValue("#heat_no", txt_heat_no.Text);
cmd.Parameters.AddWithValue("#thick", txt_shift.Text);
cmd.Parameters.AddWithValue("#width", txt_heat_no.Text);
cmd.Parameters.AddWithValue("#length", txt_length.Text);
cmd.Parameters.AddWithValue("#pcs", txt_pcs.Text);
cmd.Parameters.AddWithValue("#st_grade", txt_st_gread.Text);
cmd.Parameters.AddWithValue("#location", txt_loction.Text);
cmd.Parameters.AddWithValue("#slab_no", txt_slab_no.Text);
con.Open();
cmd.ExecuteNonQuery();
txt_heat_no.Text = cmd.ExecuteScalar().ToString();
con.Close();
MessageBox.Show("تمت عملية الإضافة");
}
}
}
cmd.Parameters.AddWithValue("#ödenecektutar", Convert.ToDecimal(tutar1.Text.Substring(0, tutar.Text.Length - 1)));

"Data type mismatch in criteria expression" when trying to delete row from database

OleDbCommand system = new OleDbCommand();
system.CommandType = CommandType.Text;
system.CommandText = "DELETE FROM Student WHERE(ID= '" +
txtStudentIDnumber.Text + "')";
system.Connection = mydatabase;
mydatabase.Open();
system.ExecuteNonQuery();
dataGridView1.Update();
this.tableAdapterManager.UpdateAll(csharrpfinalprojectDataSet);
mydatabase.Close();
MessageBox.Show("Student Record Deleted.", "deleting record...");
In your command text you need to remove single quotes (') around the txtStudentIDnumber.Text as it appears ID is of type integer and you are passing it as string. Following should fix the error.
system.CommandText = "DELETE FROM Student WHERE(ID= " + txtStudentIDnumber.Text + ")";
EDIT: With respect to #mdb comments, you should always use Parameters in your query so that you can avoid SQL Injection. Consider the following:
OleDbCommand system = new OleDbCommand();
system.CommandType = CommandType.Text;
system.CommandText = "DELETE FROM Student WHERE ID = ?";
OleDbParameter parameter = new OleDbParameter("ID", txtStudentIDnumber.Text);
system.Parameters.Add(parameter);
system.Connection = mydatabase;
mydatabase.Open();
system.ExecuteNonQuery();
dataGridView1.Update();
OleDbCommand system = new OleDbCommand();
system.CommandType = CommandType.Text;
system.CommandText = "DELETE FROM Student WHERE ID=#ID";
system.Parameters.AddWithValue("#ID", txtStudentIDnumber.Text);
system.Connection = mydatabase;
mydatabase.Open();
system.ExecuteNonQuery();
dataGridView1.Update();
this.tableAdapterManager.UpdateAll(csharrpfinalprojectDataSet);
mydatabase.Close();
MessageBox.Show("Student Record Deleted.", "deleting record...");
What will happen when user input for txtStudentIDNumber is,
1 or 1=1
In that case hardcoded SQL string will be,
DELETE FROM Student WHERE(ID=1 or 1=1)
So prefer parameterized sql statement instead of hard-coded string.
using(OleDbConnection cn=new OleDbConnection(cnStr))
{
using(OleDbCommand cmd=new OleDbCommand())
{
cmd.CommandText="DELETE FROM Student WHERE ID=#ID";
cmd.Connection=cn;
cmd.Parameters.Add("#ID",SqlDbType.Int).Value=txtStudentIDnumber.Text;
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
}
}

Dynamically passing a value inside a query?

I have two columns syntax and query in my table Table1. Syntax contains data called po and a query called select * from po_pomas_pur_order_hdr where pomas_pono =. I got this query value by using
SqlDataAdapter da = new SqlDataAdapter("select query from Table1 where syntax = '" + textBox1.Text + "'", conn);
And my problem is that I need to dynamically pass another value inside the query which I retrived using dataadapter like this:
SqlDataAdapter da1 = new SqlDataAdapter(da.tostring() +"'"+ textBox1.Text +"'", conn)
The resulting query should be like this:
select * from po_pomas_pur_order_hdr where pomas_pono = '2PO/000002/09-10'
But it is not possible. How to get a query like this? Any suggestion?
SqlDataAdapter is used to fill datasets and datatables. You cannot obtain the result of a query with ToString(). I think you want to use SqlCommand to execute your first query to retrieve the actual query to run from the database like this:
string query = null;
using (var command = new SqlCommand("select query from Table1 where syntax = #Syntax", conn))
{
command.Parameters.AddWithValue("#Syntax", textBox1.Text);
query = command.ExecuteScalar(); // this assumes only one query result is returned
}
Then you can use the data adapter to fill it:
SqlDataAdapter da1 = new SqlDataAdapter(query +"'"+ textBox1.Text +"'", conn);
Although I would suggest to use parameters for that as well.
in this way is more safe: dotnetperls
He check the "'" and the "\", check the type of the fields etc...
Code from the example above (is the same for insert delete and update):
using (SqlCommand command = new SqlCommand("SELECT * FROM Dogs1 WHERE Name LIKE #Name", connection))
{
//
// Add new SqlParameter to the command.
//
command.Parameters.Add(new SqlParameter("Name", dogName));
//
// Read in the SELECT results.
//
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
int weight = reader.GetInt32(0);
string name = reader.GetString(1);
string breed = reader.GetString(2);
Console.WriteLine("Weight = {0}, Name = {1}, Breed = {2}", weight, name, breed);
}
}
I suggest you to use SqlParameters. Here is example how to use DataAdapter and parameters.
Provided that you have a DataSet you intend to fill using the adapter and that you adjust the queries to use parameters in order to avoid sql injection you should be able to use something like this:
string query;
using(var sqlCommand = new SqlCommand(
"select query from Table1 where syntax=#syntax", conn))
{
sqlCommand.Parameters.AddWithValue("syntax", textBox1.Text);
query = (string)sqlCommand.ExecuteScalar();
}
using(var dataAdapter = new SqlDataAdapter())
using(var dataCommand = new SqlCommand(query, conn))
{
dataCommand.Parameters.AddWithValue("parameter", poNumber);
dataAdapter.SelectCommand = dataCommand;
dataAdapter.Fill(myDataSet);
}

Categories