Populate multiple text boxes with SqlDataReader - c#

I am trying to populate 11 textboxes, using my database information.
private void button5_Click(object sender, EventArgs e)
{
SqlConnection CN = new SqlConnection();
CN.ConnectionString = cons;
try
{
CN.Open();
SqlCommand cmd = new SqlCommand("SELECT FROM Lista1 WHERE DescripcionNombre = "
' + comboBox1.text + '
"",
CN)
;
SqlDataReader myReader = cmd.ExecuteReader();
}
catch
{
MessageBox.Show("You failed!");
}
}
It always fails, not even able to get that right....

The error is in this line of code
SqlCommand cmd = new SqlCommand("SELECT FROM Lista1 WHERE DescripcionNombre = "' + comboBox1.text + '"", CN);
It should be either like this
SqlCommand cmd = new SqlCommand("SELECT * FROM Lista1 WHERE DescripcionNombre = '" + comboBox1.text + """, CN);
Or
SqlCommand cmd = new SqlCommand("SELECT Column1_name, column2_name FROM Lista1 WHERE DescripcionNombre = '" + comboBox1.text + "'", CN);
As you have not selected any columns it didn't work as you expected.
And in the side note pass paramater value instead of passing the value straight from the field values. so that you can avoid SQL Injection
SqlCommand cmd = new SqlCommand("SELECT Column1_name, column2_name FROM Lista1 WHERE DescripcionNombre = #DescripcionNombre", CN);
cmd.Parameters.AddWithValue("#DescripcionNombre", comboBox1.text);

The first order of business would be to write this line properly:
SqlCommand cmd = new SqlCommand("SELECT FROM Lista1 WHERE DescripcionNombre = "' + comboBox1.text + '"", CN);
That's not valid SQL or C#. You need to specify which columns to retrieve from the table. If want all columns then use a wildcard. The next order of business is to learn how to concatenate strings. If you want single quotes to be part of the string literal then they have to be inside the double quotes.
SqlCommand cmd = new SqlCommand("SELECT * FROM Lista1 WHERE DescripcionNombre = '" + comboBox1.text + "'", CN);
That's quite elementary stuff. You should spend some time reading a tutorial or two.
Once that's done, you then need to actually read the data from the data reader. This can help with that. Note the use of parameters rather than string concatenation in those examples? You can learn more about that here.

SqlCommand cmd = new SqlCommand("SELECT FROM Lista1 WHERE DescripcionNombre = "' + comboBox1.text + '"", CN);
You are not selecting any columns or expressions in your SELECT
Your single and double quotes are backwards in the concatenation
You should get in the habit of using parameters instead of concatenating SQL (for several reasons, not the least of which is SQL Injection vulnerability)
A valid statement would be:
SqlCommand cmd = new SqlCommand("SELECT * FROM Lista1 WHERE DescripcionNombre = '"
+ comboBox1.text
+ "'", CN);

You forget to mention column name which you need to fetch in query
Always use parameterized queries How does SQLParameter prevent SQL Injection
SqlCommand cmd = new SqlCommand("SELECT * FROM Lista1 WHERE DescripcionNombre=#DescripcionNombre, CN);
cmd.Parameters.AddWithValue("#DescripcionNombre", comboBox1.text);
But your query should be like this
SqlCommand cmd = new SqlCommand("SELECT * FROM Lista1 WHERE DescripcionNombre = '" + comboBox1.text + "'", CN);

Related

syntax error (missing operator) in query expression

I'm using c# and this error is becoming headache for me. I do not know how to solve this error .
can anyone help me to solve this. Here is the code
try
{
string MyConnection2 = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\DELL\Documents\db1.mdb";
//Display query
string Query = "select riq_num , department, item_name , item_unit , no_of_stock_out , itemtype from outputdet1 where riq_num = " + textBox2.Text + " or department= '" + comboBox1.Text + " ' or item_name= '" + textBox4.Text + "' or item_unit= '" + comboBox2.Text + "' or no_of_stock_out = " + textBox6.Text + " or itemtype = '" + comboBox3.Text + "' ; ";
OleDbConnection MyConn2 = new OleDbConnection(MyConnection2);
OleDbCommand MyCommand2 = new OleDbCommand(Query, MyConn2);
MyConn2.Open();
//For offline connection we will use MySqlDataAdapter class.
OleDbDataAdapter MyAdapter = new OleDbDataAdapter();
MyAdapter.SelectCommand = MyCommand2;
DataTable dTable = new DataTable();
MyAdapter.Fill(dTable);
// here i have assign dTable object to the dataGridView1 object to display data.
dataGridView1.DataSource = dTable;
MyConn2.Close();
}
// OleDbCommand MyCommand2 = new OleDbCommand(Query, MyConn2);
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
I assumed that textBox2.Text & textBox6.Text return a string from textbox control, so that OleDbCommand will throwing exception when it contains empty value or any non-numeric string since it will form invalid SQL statement. Use parameterized query like this example:
string Query = #"select riq_num, department, item_name, item_unit, no_of_stock_out, itemtype
from outputdet1
where riq_num = #riq_num
or department= #department
or item_name= #item_name
or item_unit= #item_unit
or no_of_stock_out = #no_of_stock_out
or itemtype = #itemtype";
using (OleDbConnection MyConn2 = new OleDbConnection(MyConnection2))
{
using (OleDbCommand MyCommand2 = new OleDbCommand(Query, MyConn2))
{
MyConn2.Open();
MyCommand2.Parameters.Add("#riq_num", textBox2.Text);
MyCommand2.Parameters.Add("#department", comboBox1.Text);
MyCommand2.Parameters.Add("#item_name", textBox4.Text);
MyCommand2.Parameters.Add("#item_unit", comboBox2.Text);
MyCommand2.Parameters.Add("#no_of_stock_out", textBox6.Text);
MyCommand2.Parameters.Add("#itemtype", comboBox3.Text);
// execute the query here
}
}
Remember that using statements used to dispose OLEDB connection immediately after it has closed so that GC can free up resources.
Additional note:
OleDbParameter works with parameter order instead of named parameters, hence ensure that the parameters are declared in their proper order from first to last.

my insert command not changing the database when using through programming

When I am inserting values with query database is inserting when doing it with coding it won't insert although it show successful. Im using C# 2010 and 2012 Both are not adding
My Code
con.Open();
cmd = new SqlCommand("insert into Main_2(Name,NIC,NA_ID,PS_ID) values('" + name + "','" + nic + "',(SELECT NA_ID FROM NationalAssembly WHERE Name='" + na_name + "'),(SELECT PS_ID FROM ProvisionalAssembly Where Name='" + ps_name + "'))", con);
cmd = new SqlCommand("UPDATE ProvisionalAssembly SET Count=+1 WHERE Name='" + ps_name + "'", con);
cmd = new SqlCommand("UPDATE NationalAssembly SET Count=+1 WHERE Name='" + na_name + "'", con);
cmd.ExecuteNonQuery();
con.Close();
SqlCommand is a class, that means it is a reference types.
Everytime you create a new SqlCommand object and you assing it cmd as a reference. That means only your last SqlCommand executes. Your first two SqlCommand doesn't have a reference anymore in memory when you execute with ExecuteNonQuery method.
If you want to execute all these commands, you need to execute separately for each command.
And please use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.
Also use using statement to dispose your database connections.
using(SqlCommand cmd = new SqlCommand(YourInsertStatement))
{
con.Open();
cmd.ExecuteNonQuery();
cmd.CommandText = YourFirstUpdateStatement;
cmd.ExecuteNonQuery();
cmd.CommandText = YourSecondUpdateStatement;
cmd.ExecuteNonQuery();
}

SqlDataAdapter error in c sharp

Hello I have an error with the data adapter in c sharp . How to fix?
SqlCommand cmd = new SqlCommand("select * from View_1 where Words_Sh LIKE ' + #txbSearch + '%'", con);
cmd.Parameters.AddWithValue("#txbSearch", this.txbSearch.Text);
SqlDataAdapter da = new SqlDataAdapter(cmd, con)
;
Don't add a single quote and the plus sign before the parameter placeholder
SqlCommand cmd = new SqlCommand("select * from View_1 " +
"where Words_Sh LIKE #txbSearch + '%'", con);
Also, I prefer to concatenate the wildcard symbol directly inside the parameter value.
Not sure if it makes any difference, though, just a matter of preferences and less clutter in the query string.
SqlCommand cmd = new SqlCommand("select * from View_1 " +
"where Words_Sh LIKE #txbSearch", con);
cmd.Parameters.AddWithValue("#txbSearch", this.txbSearch.Text + "%");
EXAMPLE:
string commandText = "select * from View_1 " + "where Words_Sh LIKE #parameters"
cmd.Parameters.AddWithValue("#parameters", "Parameter 1");
Because of starting double quote, you should finish with double quotes before plus sign, but you can use single quote before double quote for LIKE operation.
SqlCommand cmd = new SqlCommand("select * from View_1 where Words_Sh LIKE '#txbSearch%'", con);
cmd.Parameters.AddWithValue("#txbSearch", this.txbSearch.Text);
SqlDataAdapter da = new SqlDataAdapter(cmd, con);
SqlConnection con = new SqlConnection("");
SqlCommand cmd = new SqlCommand("select * from View_1 where Words_Sh LIKE ' + #txbSearch + '%'", con);
cmd.Parameters.AddWithValue("#txbSearch", this.txbSearch.Text);
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;

Search record in ACCESS DATABASE using c#

i am trying to find the records based on the user input in msaccess database.
below is the code
string strProvider = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Employees.mdb";
string strSql = "SELECT * FROM tbl_employees where description like '" + txtsearch.Text.ToString() + "*'";
OleDbConnection con = new OleDbConnection(strProvider);
OleDbCommand cmd = new OleDbCommand(strSql, con);
con.Open();
cmd.CommandType = CommandType.Text;
OleDbDataReader dr = cmd.ExecuteReader();
int columnCount = dr.FieldCount;
When i ran the same query in my SQLView of msaccess i am getting records but when i ran it in VS i am not getting any records.
I think your matching should be changed:
String strSql = "SELECT * FROM tbl_employees WHERE description LIKE '" + txtsearch.Text.ToString() + "%'";
//Replaced * with %

Shortening data access code... would this work?

I am querying for data, if the data does not exist, I insert it. if it does, I do something else:
SqlCommand checkHead = new SqlCommand("SELECT * FROM TABLE WHERE ORDER_NO = '" + orderNo + "';", connection);
SqlDataReader checkHeadReader = checkHead.ExecuteReader(CommandBehavior.SingleRow);
if (!checkHeadReader.HasRows)
{
checkHeadReader.Close();
addHead.ExecuteNonQuery();
}
But I wonder if there's a shorter way to code this? would the code below work?
SqlCommand checkHead = new SqlCommand("SELECT * FROM TABLE WHERE ORDER_NO = ' + orderNo + "';", connection);
if(checkHead.ExecuteReader(CommandBehavior.SingleRow).HasRows)
addHead.ExecuteNonQuery();
else //this order already exists
Server.Transfer(#"~/Views/Error.aspx");
ExecuteScalar is great for this, E.g.
using (SqlCommand cmdCheck = new SqlCommand("Select Count(*) From Table Where Order_No = '" + orderNo + "'", connection))
{
int nExists = (int)cmdCheck.ExecuteScalar();
if (nExists==0) addHead.ExecuteNonQuery();
}

Categories

Resources