Search record in ACCESS DATABASE using c# - 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 %

Related

How to insert in c# using custom table name

This is partial code which i try
SqlConnection con = new SqlConnection(#"Data Source=ANSARI-PC\;Initial Catalog=BMS;Integrated Security=True");
string tname = idc + "-InvoiceT";
string sql = "select count(*) from '"+ tname + "' ";
con.Open();
SqlCommand sda = new SqlCommand(sql, con);
SqlDataReader myreader;
myreader = sda.ExecuteReader();
int lid;
For above code im getting this error Incorrect syntax near '2-InvoiceT'
2-InvoiceT is table name in database 'idc' contain 2 as value.
Change
string sql = "select count(*) from '"+ tname + "' ";
to
string sql = "select count(*) from ["+ tname + "] ";

How can I save a variable from a database and use it in C#?

I am changing a program and I need some help because I don't know C#. I change things with:
strSQL = "UPDATE materials SET ";
strSQL = strSQL + "Dscr = 'concrete', ";
strSQL = strSQL + "width=50 ";
strSQL = strSQL + " WHERE ID=385";
objCmd = new OleDbCommand(strSQL, db_def.conn);
objCmd.ExecuteNonQuery();
There is a case where I need to find an ID, store it and then use it again. So I use select
OleDbCommand cmd = new OleDbCommand("SELECT ID FROM materials WHERE Type=1", db_def.conn);
OleDbDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
{
reader.Read();
var result = reader.GetInt32(0);
}
strSQL = "UPDATE materials SET ";
strSQL = strSQL + "Dscr = 'concrete', ";
strSQL = strSQL + "width=50 ";
strSQL = strSQL + " WHERE ID=result";
objCmd = new OleDbCommand(strSQL, db_def.conn);
objCmd.ExecuteNonQuery();
But I get an error:
No value given for one or more required parameters.
you can try this and tell me if it works
OleDbCommand cmd = new OleDbCommand("SELECT ID FROM materials WHERE Type=1", db_def.conn);
OleDbDataReader reader = cmd.ExecuteReader();
int result=-1 ;
if (reader.HasRows)
{
reader.Read();
result = reader.GetInt32(0);
}
if (result != -1)
{
strSQL = "UPDATE materials SET ";
strSQL = strSQL + "Dscr = 'concrete', ";
strSQL = strSQL + "width=50 ";
strSQL = strSQL + " WHERE ID="+result;
objCmd = new OleDbCommand(strSQL, db_def.conn);
objCmd.ExecuteNonQuery();
}
Although your code that you're working on is less than desirable, I'll just provide the fix you require at this point:
Change your code to :
OleDbCommand cmd = new OleDbCommand("SELECT ID FROM materials WHERE Type=1", db_def.conn);
OleDbDataReader reader = cmd.ExecuteReader();
int result=0;
if (reader.HasRows)
{
reader.Read();
result = reader.GetInt32(0);
}
strSQL = "UPDATE materials SET ";
strSQL = strSQL + "Dscr = 'concrete', ";
strSQL = strSQL + "width=50 ";
strSQL = strSQL + " WHERE ID=" + result;
objCmd = new OleDbCommand(strSQL, db_def.conn);
objCmd.ExecuteNonQuery();
You need to provide the value of the result variable outside the SQL string - the database will not know the value of 'result' in its own context.
EDIT: the result variable was declared within the if statement, therefore not available further down for assigning.

Populate multiple text boxes with SqlDataReader

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);

Getting Data from Access into a text box in C# by clicking a button

I have a table in MS Access that contain: (FoodID, FoodName, Price).
In C# I have three text boxes (txtId, txtName, txtPrice) and a button (btnSearch).
My question is that, In C# I just type FoodID in (txtId) and then click on button Search It'll display FoodName and Price ( from table access) in txtName and txtPrice by itself. I got the source code from you but it error on (OleDbDataReader dr = cmd.ExecuteReader();) its message is "Data type mismatch in criteria expression" .
Please solve this problem for me. This is the whole source code that I got for you.
System.Data.OleDb.OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = "your connection string";
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;
cmd.CommandText = "select FoodName, Price from tablename where FoodID = '" + txtId + "' ";
conn.Open();
OleDbDataReader dr = cmd.ExecuteReader();//error this line!
while(dr.Read())
{
txtName.Text = dr["FoodName"].ToString();
txtPrice.Text = dr["Price"].ToString();
}
dr.Close();
conn.Close();
I assume FoodID is int. You should remove single quotes in this case
cmd.CommandText = "select FoodName, Price from tablename where FoodID = " + txtId;
Even better - use parameters:
using (var connection = new OleDbConnection("your connection string"))
using (var command = connection.CreateCommand())
{
command.CommandText = "select FoodName, Price from tablename where FoodID = #FoodID";
command.Parameters.AddWithValue("FoodID", int.Parse(txtId.Text));
connection.Open();
var reader = command.ExecuteReader();
while (reader.Read())
{
txtName.Text = reader["FoodName"].ToString();
txtPrice.Text = reader["Price"].ToString();
}
}
I think the FoodId is of Integer type in the database but over here in the query you have passed as string so convert the string to integer.
cmd.CommandText = "select FoodName, Price from tablename where FoodID = '" + int.Parse(txtId.Text) + "' " ;
There seems to be no problem with this line of code :
OleDbDataReader dr = cmd.ExecuteReader();// correct way
I think the problem is in:
cmd.CommandText = "select FoodName, Price from tablename where FoodID = '" + txtId + "' ";
You need to use the .Text Propertie of the Textbox
cmd.CommandText = "select FoodName, Price from tablename where FoodID = '" + txtId.Text + "' ";

C# SQL Columns into ComboBox

My SQL query isn't dropping anything into the combobox. The connection seems to be made but the while loop doesn't seem to work. Can anybody tell me what it wrong?
string sqltable = ("dbo.SLTDS_C"+id+"_table");
SqlConnection con = new SqlConnection("Data Source=" + server + ";Initial Catalog=" + database + ";Integrated Security=" + security);
con.Open();
string sqldatapull = ("select name from syscolumns where id = object_id('" + sqltable + "') order by name asc");
SqlCommand cmd = new SqlCommand(sqldatapull, con);
cmd.CommandType = CommandType.Text;
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
sqldatapull = dr[0].ToString();
comboBox1.Items.Add(sqldatapull);
}
dr.Close();
con.Close();
Correction code:
string sqldatapull = ("select name from syscolumns where id = object_id('" + sqltable + "') order by name asc");
It's because you're including dbo. as part of the table name. If you run
SELECT * FROM INFORMATION_SCHEMA.COLUMNS
You will see that the table names have no schema in the TABLE_NAME column.

Categories

Resources