i want to check valid data...
i have a table Divisi with sample data like this:
=====================
IdDivisi NamaDivisi
=====================
1 DivisiA
2 DivisiB
3 DivisiC
in my code, i get value :
string data = DivisiA;DivXXX
so, when checked, the alert will appear invalid data.
I want to get a query like this:
select NamaDivisi from Divisi where NamaDivisi IN('DivisiA','DivXXX')
and the result is null or empty or invalid.
because there are values / data 'DivXXX' is not valid on the table Divisi
But this time, when I debug, I get the query result like this:
select NamaDivisi from Divisi where NamaDivisi IN ('DivisiA;DivXXX')
===================================================
This is the full code.
private string CekValidDivisi(string data)
{
DivisiFacade div = new DivisiFacade();
string getDivisi = div.CekValidData(data);
return getDivisi;
}
public string CekValidData(string data)
{
SqlConnection Conn = DataSetting.GetSqlConnection();
SqlCommand Comm = new SqlCommand();
try
{
Conn.Open();
string sql = #"select NamaDivisi from Divisi where NamaDivisi IN('" + data + "')";
Comm = new SqlCommand(sql, Conn);
data = Convert.ToString(Comm.ExecuteScalar());
}
finally
{
Conn.Close();
Conn.Dispose();
}
return data;
}
please help me to resolve the problem in my code. thank you ...
You have multiple problems in your code, but this is not a place to teach you basics, so I'll try to stick to the topic. If you want to have a parameter like that, you have to create it like that first. I guess the data contains string with value DivisiA;DivXXX (and I presume DivXXX is just a generic name meaning you have multiple divisions there). Probably the easiest way would be to do something like this with it
public string CekValidData(string data)
{
SqlConnection Conn = DataSetting.GetSqlConnection();
SqlCommand Comm = new SqlCommand();
try
{
Conn.Open();
string paramData = ParseData(data);
string sql = #"select NamaDivisi from Divisi where NamaDivisi IN('" + paramData + "')";
Comm = new SqlCommand(sql, Conn);
data = Convert.ToString(Comm.ExecuteScalar());
}
finally
{
Conn.Close();
Conn.Dispose();
}
return data;
}
private string ParseData(string data)
{
return data.Replace(";", "','");
}
Haven't tried it, but hope you get the idea. Either way, please for your own sake, do some research on what is the best way to handle sql connections in c# and also how to prevent SQL injections.
Related
When i run my code in the debugger and I hover my mouse over the parameters they do have the right values in them. It just doesn't update my database but when I copy the query and put it into the database it works without a problem.
The parameter values are:
id = 7
omschrijving = douche muntjes
prijs = 0,5
catagorie = faciliteiten
I checked the connection tring by using an insert query and that does add records to my database. And There is an id with the value of 7 in the database.
When I run a insert query or a delete query through my C# code it does work it's just the update statement that doesn't work. If anyone sees the issue please help me.
public static void wijzigprijs(int id, string omschrijving, decimal prijs, string catagorie)
{
try
{
try
{
OleDbConnection verbinding = new OleDbConnection(
#"Provider=Microsoft.ACE.OLEDB.12.0;
Data Source=..\..\..\La_Rustique.accdb;
Persist Security Info=False;");
verbinding.Open();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
OleDbCommand query = new OleDbCommand();
query.CommandText = #"UPDATE prijslijst
SET omschrijving = #omschrijving,
prijs = #prijs,
catagorie = #catagorie
WHERE id = #id";
query.Parameters.Add(new OleDbParameter("#id", OleDbType.Integer));
query.Parameters["#id"].Value = id;
query.Parameters.Add(new OleDbParameter("#omschrijving", OleDbType.VarChar));
query.Parameters["#omschrijving"].Value = omschrijving;
query.Parameters.Add(new OleDbParameter("#prijs", OleDbType.Decimal));
query.Parameters["#prijs"].Value = prijs;
query.Parameters.Add(new OleDbParameter("#catagorie", OleDbType.VarChar));
query.Parameters["#catagorie"].Value = catagorie;
query.Connection = verbinding;
query.ExecuteNonQuery();
MessageBox.Show("succesvol gewijzigd");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
verbinding.Close();
}
}
EDIT UPDATE
Look at this topic. Here he explains how you should use variables with OleDbCommand
Variables with OleDbCommand
This is how you typically will do it when using SQLCommand parameters:
I know this doesnt answer your questions quite, but when i use SQLCommand i use this code whenever i want to update or insert with variables:
string query = #"UPDATE prijslijst
SET omschrijving = #omschrijving,
prijs = #prijs,
catagorie = #catagorie
WHERE id = #id";
SqlCommand cmd = new SqlCommand(query, connDatabase);
cmd.Parameters.Add("#id", SqlDbType.integer).Value = 7;
cmd.ExecuteNonQuery();
connDatabase.Close();
So you should be able to do the samething. Hope this will help you.
I have never seen OleDB queries written in the above syntax.
To state it differently: OleDB simply does not use named parameters, it uses the position only.
Try to change your SQL statement like this:
query.CommandText = #"UPDATE prijslijst
SET omschrijving = ?,
prijs = ?,
catagorie = ?
WHERE id = ?";
and then add the parameters in sequence of above in the code
below that.
Case: I'm trying execute a query in C# with MySql.Data.MySqlClient, which containts INSERT INTO, i'm getting an error(see below):
Database table:
What im trying to achieve: I want to insert into a new record with: "value_id(Auto Increment)", "machine_id" "tag_name", "int_value", "real_value" and "bool_value";
I have the following code:
*Retrieving machine ID
private void getMachineID()
{
string connStr = "";
string ipAdressID = "'" + machineIP + "'";
string basicQueryID = "SELECT machine_id FROM machine WHERE machine.machine_ip LIKE ";
string totalQueryID = basicQueryID + ipAdressID;
//Create connection
MySqlConnection conn = new MySqlConnection(connStr);
//Query command
MySqlCommand cmd = conn.CreateCommand();
//Assign string to query
cmd.CommandText = totalQueryID;
//Open connection
conn.Open();
//Get result ID from machine where IP adress = machineIP and write to machineID variable.
machineID = (int)(cmd.ExecuteScalar());
}
Code to insert into the record:
try
{
string connStr = "";
MySqlConnection conn = new MySqlConnection(connStr);
MySqlCommand cmd = conn.CreateCommand();
cmd.CommandText = "INSERT INTO waardes(machine_id, tag_name, int_value, real_value, bool_value) VALUES(#machineID, #tagName, #intValue, #doubleValue, #boolValue)";
cmd.Parameters.AddWithValue("#tagName", tagName);
cmd.Parameters.AddWithValue("#intValue", intValue);
cmd.Parameters.AddWithValue("#doubleValue", doubleValue);
cmd.Parameters.AddWithValue("#boolValue", boolValue);
cmd.Parameters.AddWithValue("#machineID", machineID);
conn.Open();
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
Hope you guys can help!
There's no INSERT with where clause.
Take a look at this question: How to insert with where clause
Maybe, you can create an IF inside your app to verify your parameters before executing the INSERT statement.
Based on your query, I believe you need an UPDATE:
UPDATE waardes SET tag_name = #tagName,
int_value = #intValue, real_value = #doubleValue,
bool_value = #boolValue WHERE machine.machine_id LIKE %1%
Is this what you need?
you cannot use where in insert statement, because insert statement is used for adding new rows to table. you better use update statement.
There can be no Where clause used with Insert. However you can use Where when you are using Insert Into. In your statement I suppose you are missing the Select From before your Where clause.
Consider the example:
INSERT INTO tableNameDestination
SELECT feild(s),...
FROM tableNameSource
WHERE Condition
In your case:
INSERT INTO waardes(tag_name, int_value, real_value, bool_value) VALUES(#tagName, #intValue, #doubleValue, #boolValue) Select field1, field2, field3, field4 from machine WHERE machine.machine_id LIKE " + "'" + machineID + "'";
I am trying to store each row of a access database, based on column Veh_ID. The found data may or may not be based on multiple rows. The code I am currently using can copy single row but if there are multiple results I can only get the first result. Can anyone please help me on this? I am noob when it comes to database. I tried to search Google but no one seems to be needing what I need. Here's the code I'm using:
string cmd1 = "SELECT * FROM Veh_checkup WHERE Veh_ID = " + veh_idd + "";
OleDbCommand cmd = new OleDbCommand(cmd1, con);
OleDbDataReader read = cmd.ExecuteReader();
read.Read();
veh_id=null;
int i=0;
foreach (var a in read)
{
try
{
veh_id = veh_id + " " + read[i].ToString();
}
catch { }
i++;
}
There are a few things I would point out, some specific to your question, some not:
USE PARAMETERISED QUERIES
Use OleDbDataReader.Read() to move to the next record.
Use a StringBuilder to concatenate strings in a loop, using string = string + "something" will create a new string on the heap with each iteration
Use using blocks on Disposable objects
catch { } is not good practice. You will never know an error occurred. At the very least you should log the error somewhere so you know you need to fix something.
OleDbDataReader[i] will get the data from column i for the current record being read, not the data from row i
Don't use SELECT * in production code, especially if you are only using 1 column. It is unnecessary data retrieval from the database and also unnecessary network traffic.
USE PARAMETERISED QUERIES
Okay, I know I included using parameterised queries twice, but that is how strongly I feel about it!
With the above changes made, your full code will become something like:
static string GetStringData(string vehID)
{
StringBuilder builder = new StringBuilder();
string cmd1 = "SELECT Column1 FROM Veh_checkup WHERE Veh_ID = #VehID";
using (OleDbConnection con = new OleDbConnection("YourConnectionString"))
using (OleDbCommand cmd = new OleDbCommand(cmd1, con))
{
con.Open();
cmd.Parameters.AddWithValue("#VehID", vehID);
using (OleDbDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
builder.Append(" " + reader.GetString(0));
}
}
}
return builder.ToString();
}
You are using the datareader in a wrong way. Instead of calling it once like you do, you have to call the datareader in a while loop like this:
while(theDataReader.Read())
{
// do your stuff in a loop now
}
So using this approach in your code would look something like this:
string cmd1 = "SELECT * FROM Veh_checkup WHERE Veh_ID = " + veh_idd + "";
OleDbCommand cmd = new OleDbCommand(cmd1, con);
OleDbDataReader read = cmd.ExecuteReader();
veh_id=null;
con.Open();
while(read.Read()) //your reader
{
try
{
veh_id = veh_id + " " + read[i].ToString();
}
catch { }
}
At the moment i have a textbox and a button and i can read the textbox fine and it searches the databse for say "apple"
but if there is a result called "red apple" it will not return it.
I have tried
string getTheBox = (this.searchBox.Text);
string request = "%" + getTheBox + "%";
But it doesn't seem to be working. This is with "request" being the string variable.
EDIT to include the SQL request part
SqlDataSource2.SelectCommand = "SELECT Recipe_Name FROM New_Recipe WHERE [ingredient1]=#request
SqlDataSource2.SelectParameters.Add(newParameter("request",System.TypeCode.String));
SqlDataSource2.SelectParameters["request"].DefaultValue = request;
The adding of % is correct, but you need to change your sql query
you need to use the LIKE operator
for example THE QUERY could be
"SELECT Recipe_Name FROM New_Recipe WHERE ingredient1 LIKE #request"
and your code
string request = "%" + getTheBox + "%";
string sqlText = "SELECT Recipe_Name FROM New_Recipe WHERE ingredient1 LIKE #request";
using(SqlConnection cn = GetSqlConnection())
{
cn.Open();
using(SqlCommand cmd = new SqlCommand(sqlText, cm);
{
cmd.Parameters.AddWithValue("#request", request);
SqlDataReader dr = cmd.ExecuteReader();
while(dr.Read())
{
......
}
}
}
Please post your SQL query too. Perhaps you need to change WHERE FruitName = #FruitName to WHERE FruitName LIKE #FruitName
This is a horrible idea, as anyone can run sql injection. You probably want something akin to
Sqlcommand.Prepare
As it will let you set safer arguements. And have two words.
I usually have a few helper functions to add like to my queries depending on what I need done.
public List<T> GetRecipesThatContain<T>(string ingredient)
{
const string commandText = "SELECT Recipe_Name FROM New_Recipe WHERE ingredient1 LIKE #SearchTerm";
var searchTerm = Contains(ingredient);
using(var connection = GetSqlConnection())
{
connection.Open();
using(var command = new SqlCommand(commandText, connection);
{
command.Parameters.AddWithValue("#SearchTerm", searchTerm);
using(var reader = command.ExecuteReader())
{
var results = new List<T>();
while(reader.Read())
{
// Get results
// results.Add(result);
}
return results;
}
}
}
}
private string StartsWith(string searchTerm)
{
return string.Format("{0}%", searchTerm);
}
private string EndsWith(string searchTerm)
{
return string.Format("%{0}", searchTerm);
}
private string Contains(string searchTerm)
{
return string.Format("%{0}%", searchTerm);
}
Here is a background on my program: each protein is made from a sequence of amino acids(or AA)
I have some tables :tblProInfo(that contains general info about proteins),tblOrderAA(that contains the sequence(AA sequence) of specific protein(for each protein there is a serial number that i set before))
now, I'm trying to retvive the science names of the protein that contains part of sequence that the user put in textbox1. It is likely that more than one protein contains the sequence that the user typed.
Here is my code. I got "Syntax error" and I'm sure I have more mistakes.Please HELP me!
public void OpenDB()
{
dataConnection = new OleDbConnection();
try
{
dataConnection.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Projects_2012\\Project_Noam\\Access\\myProject.accdb";
dataConnection.Open();
}
catch (Exception e)
{
MessageBox.Show("Error accessing the database: " +
e.Message,
"Errors",
MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
private string FromCodonsToProtein(string codons)
{
OpenDB();
int sizePro=0, i,counter=0,serialPro;
string st="",tempst="";
OleDbCommand datacommand = new OleDbCommand();
datacommand.Connection = dataConnection;
datacommand.CommandText = "SELECT tblProInfo.proInfoAAnum, tblProInfo.proInfoSerialNum,tblProInfo.proInfoScienceName FROM tblProInfo";
OleDbDataReader dataReader = datacommand.ExecuteReader();
while(dataReader.Read())
{
sizePro = dataReader.GetInt32(counter);
serialPro= dataReader.GetInt32(counter+1);
counter++;
OleDbCommand cmd= new OleDbCommand();
cmd.Connection = dataConnection;
cmd.CommandText = "SELECT tblOrderAA.orderAACodon1 FROM tblOrderAA"
+"WHERE (((tblOrderAA.orderAASerialPro)='"+serialPro+"'))";
OleDbDataReader rdr = cmd.ExecuteReader();
tempst="";
for (i = 0; i > sizePro; i++)
{
tempst = tempst + rdr.GetString(i);
}
if (tempst.Contains(codons))
{
st = st + " \n" + dataReader.GetString(counter);
}
}
return st;
}
Missing a space here
cmd.CommandText = "SELECT tblOrderAA.orderAACodon1 FROM tblOrderAA"
+"WHERE (((tblOrderAA.orderAASerialPro)='"+serialPro+"'))";
rewrite in this way
cmd.CommandText = "SELECT tblOrderAA.orderAACodon1 FROM tblOrderAA"
+" WHERE (((tblOrderAA.orderAASerialPro)='"+serialPro+"'))";
// ^ here
However you should use parametrized query (also with msaccess) to avoid possible errors and injection attacks.
Another problem is the global dataConnection. Don't do that, you gain nothing in this way.
Return the connection and encapsulate it with a using statement.
For example:
public OleDbConnection OpenDB()
{
dataConnection = new OleDbConnection();
dataConnection.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Projects_2012\\Project_Noam\\Access\\myProject.accdb";
dataConnection.Open();
return dataConnection;
}
then in the calling code use this syntax
using(OleDbConnection cnn = OpenDB())
{
// in the rest of your code, replace dataConnection with cnn
// The using statement will ensure that in the case of exceptions
// your connection will be allways closed and properly disposed
........
}
EDIT: Can't give you a full working solutions, too many aspects of your problem are unknown to me, however a great simplification will be to change your query in this way
SELECT DISTINCT
tblProInfo.proInfoAAnum,
tblProInfo.proInfoSerialNum,
tblProInfo.proInfoScienceName
FROM tblProInfo LEFT JOIN tblOrderAA
ON tblOrderAA.orderAASerialPro = tblProInfo.proInfoSerialNum
WHERE tblOrderAA.orderAACodon1 = #codons
Try it directly in access using its query editor, if it works as you expected then change your code. You don't need two query and crossed loops to get the results.