Select * From table Where column Like statement c# - c#

I failed to get the correct result with this code in Form2:
conn.Open();
OleDbCommand cmd = new OleDbCommand("Select * From udbTable Where Username Like '" + f1.textBox1.Text + "%'", conn);
OleDbDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
label5.Text = reader["Username"].ToString();
}
conn.Close();
I have 3 samples data in the table, but i'm always getting the same result which is the first entry of the database. Whenever i input the last entry or second entry in the textbox1.Text, i still getting the first entry.
textbox1.Text is from Form1, and i set it's property Modification to Public.
label5.text is the output.

try this fix
conn.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection=conn;
command.CommandText = "Select * From udbTable Where Username Like ?";
cmd.Parameters.Add("#Username",OleDbType.VarChar);
cmd.Parameters["#Username"].Value=f1.textBox1.Text;
OleDbDataReader reader = cmd.ExecuteReader();

Related

Received values from my SQL query are displayed incorrect in my Listbox

I'm trying to get values out of my database into my Listbox, I currently send all my results into a new object called Results
I want my listbox to show something like this:
Title(1)(enter)
Url(1)(enter)
Title(2)(enter)
Url(2)(enter)
and so on
It currently still gives an error at OleDbDataReader reader = command.ExecuteReader(); but I have no idea why.
This is the exact code
OleDbConnection connection = new OleDbConnection();
connection.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\martijn\Dropbox\Proftaak Periode 2 Identity\Database11.accdb;
Persist Security Info=False;";
connection.Open();
OleDbCommand cmd1 = new OleDbCommand();
cmd1.Connection = connection;
cmd1.CommandText = "SELECT ZoekcriteriaID from Zoekcriteria WHERE ZoekCriteria = '" + Convert.ToString(lbzoektermen.SelectedItem) + "';";
OleDbDataReader reader1 = cmd1.ExecuteReader();
if(reader1.Read())
{
resultaatid = Convert.ToInt32(reader1["ZoekcriteriaID"]);
}
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = "SELECT Titel, Webadress from Resultaat WHERE ZoekriteriaID = '"+ resultaatid +"';";
OleDbDataReader reader = command.ExecuteReader();
lbresultaten.Items.Clear();
List<Results> resultaten = new List<Results>();
while(reader.Read())
{
Results result = new Results();
result.url = Convert.ToString(reader["Webadress"]);
result.titel = Convert.ToString(reader["Webadress"]);
resultaten.Add(result);
}
foreach(Results result in resultaten )
{
lbresultaten.Items.Add(result.titel);
lbresultaten.Items.Add(result.url);
}
I hope someone could help me,
Kind Regards,
Martijn
Your problem probably lays in your where clause:
SELECT ZoekcriteriaID from Zoekcriteria WHERE **ZoekCriteria**
It should be a column name, not a table name.

C# checking if order number already exists

I've been looking into How to check user id already exists to see how to do this.
I am trying to get this working in my code, however it's not working. I don't get errors or something, but it just write data in database even if order number already exists.
The function:
private void createorderButton_Click(object sender, EventArgs e)
{
SqlConnection myConnection = dbHelper.initiallizeDB();
String query = "INSERT INTO testtabel (knaam, korder) VALUES ('" + knaamTextBox.Text + "','" + kordernrTextBox.Text + "')";
SqlCommand sqlCommand = new SqlCommand(query, myConnection);
SqlCommand cmd = new SqlCommand("select * from testtabel where korder = #korder", myConnection);
SqlParameter param = new SqlParameter();
param.ParameterName = "#korder";
param.Value = kordernrTextBox.Text;
cmd.Parameters.Add(param);
//sqlCommand.Connection.Open();
SqlDataReader reader = sqlCommand.ExecuteReader();
if (reader.HasRows)
{
MessageBox.Show("Order already exist");
}
else
{
reader.Close();
}
// opens execute non query
int rows_inserted = sqlCommand.ExecuteNonQuery();
if (rows_inserted > 0)
{
label2.Text = "Order has been created";
}
else
{
Console.Write("Oops! Something wrong!");
}
}
Sorry for this kinda well known and duplicated question, but for some reason I can't get it working.
You called the wrong command, change
SqlDataReader reader = sqlCommand.ExecuteReader();
to
SqlDataReader reader = cmd.ExecuteReader();
The problem is here:
SqlDataReader reader = sqlCommand.ExecuteReader();
You should execute the other command first
SqlCommand cmd = new SqlCommand("select * from testtabel where korder = #korder", myConnection);
The latter command, when will be executed will tell you if there is any record in the testtabel table. If there is, then you should show the message:
Order already exist
Otherwise, you will execute your first command, that will insert the rows.
By the way, please try to avoid string concatenation, when you write sql queries. It is one of the most well known security holes. You code is open to SQL injections. You could use parameterized queries:
String query = "INSERT INTO testtabel (knaam, korder) VALUES (#knaam, #korder)";
SqlCommand sqlCommand = new SqlCommand(query, myConnection);
sqlCommand.Parameters.Add(new SqlParamete("#knaam",knaamTextBox.Text));
sqlCommand.Parameters.Add(new SqlParamete("#korder",kordernrTextBox.Text));
While your code is full of problems (magic pushbutton, SQL injections, absence of usings), there is main one. The approach you want to implement will fail on concurrent inserts, and must not be used.
Imagine, that two users run this code against the same database, using the same korder value:
1st executes SELECT - record with the given value doesn't exist;
2nd executes SELECT - record with the given value doesn't exist;
1st executes INSERT - record with the given value does exist;
2nd executes INSERT - ooops... we have a duplicate;
To avoid duplicates you must use unique indexes in database. Do not rely on your code.
You check HasRows for INSERT INTO testtabel bla...bla..bla.. not for `elect * from testtabel where korder'
Maybe you can use this (it comes from my head and not compiled, please adjust it with your own case)
private void createorderButton_Click(object sender, EventArgs e)
{
SqlConnection myConnection = dbHelper.initiallizeDB();
String query = "INSERT INTO testtabel (knaam, korder) VALUES ('" + knaamTextBox.Text + "','" + kordernrTextBox.Text + "')";
SqlCommand sqlCommand = new SqlCommand(query, myConnection);
SqlCommand cmd = new SqlCommand("select * from testtabel where korder = #korder", myConnection);
SqlParameter param = new SqlParameter();
param.ParameterName = "#korder";
param.Value = kordernrTextBox.Text;
//sqlCommand.Connection.Open();
SqlDataReader cmdReader = sqlCommand.ExecuteReader();
if (cmdReader.HasRows)
{
MessageBox.Show("Order already exist");
}
else
{
cmdReader.Close();
}
SqlDataReader reader = sqlCommand.ExecuteReader();
// opens execute non query
int rows_inserted = sqlCommand.ExecuteNonQuery();
if (rows_inserted > 0)
{
label2.Text = "Order has been created";
}
else
{
Console.Write("Oops! Something wrong!");
}
}

Display database values in textbox

I have a datatable with 2 columns, ID and Name, I have populated my combobox with the column ID.
string Query = "SELECT * FROM [Database]";
OleDbConnection me = new OleDbConnection(connection);
OleDbCommand constr = new OleDbCommand(Query, me);
me.Open();
OleDbDataReader reader = constr.ExecuteReader();
while(reader.Read())
{
textBox15.Text = (reader["Name"].ToString());
}
reader.Close();
When I select an item from the combobox, I want to retrieve values from the Column Name in the same row. For instance I select a value from my combobox which is in datarow 1 and it matches the datarow 1 in the table Name
Is there anyway to do this?
I am currently here
{
string Query = "SELECT * FROM [Database] where Name ='" + comboBox6.Text + "' "; string y = textBox15.Text
OleDbConnection me = new OleDbConnection(connection);
OleDbCommand constr = new OleDbCommand(Query, me);
me.Open();
OleDbDataReader reader = constr.ExecuteReader();
constr.Parameters.Add(new OleDbParameter("#Name", y));
while (reader.Read())
{
textBox15.Text = reader["Name"].ToString();
}
me.Close();
}
}
I am still getting an error "No parameters given for one or more values" I am sure that the code is right.
You'll need to add a parameter to your SQL query. For example:
string myName = myComboBox.SelectedItem.Text;
string Query = "SELECT * FROM [Database] WHERE Name = ?";
OleDbConnection conn = new OleDbConnection(connection);
OleDbCommand cmd = new OleDbCommand(Query, conn);
cmd.Parameters.Add(new OleDbParameter("#name", myName));
conn.Open();
OleDbDataReader reader = cmd.ExecuteReader();
while(reader.Read())
etc...
I'm not sure of the exact syntax for the OLE DB .NET Provider, but hopefully this helps somewhat.

Asp.net Getting values from access database

I am trying to get all the details of a User in an Access database. But i cant seem to save each columns value to a label. Here is the code i am using.
Also UserId has a value assigned to it already
string connString = (#"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=DataDirectory|HorseDB.mdb");
OleDbConnection conn = new OleDbConnection(connString);
conn.Open();
OleDbCommand cmd = conn.CreateCommand();
cmd.CommandText = #"SELECT * FROM [Users] WHERE [UserId] = #UserId ";
cmd.Parameters.AddWithValue("#UserId", UserId);
OleDbDataReader dbReader = cmd.ExecuteReader();
while (dbReader.Read())
{
accountUserIdLabel.Text = dbReader.GetValue(0).ToString();
//Will add other labels once this works
}
dbReader.Close();
conn.Close();

I don't get the while loop executed

I can't make out what is the mistake. I wanted to retrieve a record from the database table and give them out. There are 9 fields in my table. The data of the second field is the search word. There can be more than one record for the same data. If there are many, then it must show each record at a time. How is it possible to code it?
I use C#.Net for logic and Ms Access for the back end(Database)
This is my code:
string[] arr = new string[9];
OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source="C:\PassWordSaver\Passwords.mdb;Persist Security Info=True;");
con.Open();
OleDbCommand cmd = new OleDbCommand("SELECT * FROM pwd Where Title = '"+textBox2+"'", con);
OleDbDataReader reader = cmd.ExecuteReader();
reader.Read();
//while (reader.Read())
//{
for (int i = 0; i < 9; i++)
{
arr[i] = reader.GetValue(i).ToString();
MessageBox.Show("The New data is " + arr[i] + ".", "Created", MessageBoxButtons.OK);
}
//}
reader.Close();
MessageBox.Show("Data Added Successfully. " + arr[2] + " is the user name.", "Created", MessageBoxButtons.OK);
OleDbCommand cmd = new OleDbCommand("SELECT * FROM pwd Where Title = '"+textBox2+"'", con);
Should read:
OleDbCommand cmd = new OleDbCommand("SELECT * FROM pwd Where Title = '"+textBox2.Text+"'", con);
The reason you aren't entering your while loop is that the condition isn't being met to begin with. There is nothing for myReader to read. However, I don't understand why you don't get an error when you run that telling you that you can't convert a textbox control to a string.
First of all you're getting into the loop because your query doesn't return any results, and second of all you might want to try and put some parameters on this query like so:
OleDbCommand cmd = new OleDbCommand("SELECT * FROM pwd Where Title = ?", con);
cmd.Parameters.Add(textBox2.Text); // I assume you mean textBox2.Text
May be it will be a silly answer but I think you are trying to send query by taking the value from textbox.Text property. But on the code you are trying to get directly Textbox
OleDbCommand cmd = new OleDbCommand("SELECT * FROM pwd Where Title = '"+textBox2+"'", con);
I think you can update as follows
OleDbCommand cmd = new OleDbCommand("SELECT * FROM pwd Where Title = '"+textBox2.Text+"'", con);

Categories

Resources