I am building an intranet for my school project inside a form application using the .NET framework and the C# language. This function populates a data grid inside a form. However, the code inside the while structure won't run. I have gone step by step with the debugger, and I reckon the read() method of the "dr" object will not go trough my two inner joined tables, but when I press a button that i have set to show me how many books are there registered in the database, it works. I think there is something wrong with my SQL statement, by what I have searched on this site, but I did not manage to resolve the bug. Carti.Nota and Carti.Stoc are columns with the Number type inside a Microsoft Access 2013 Database.
private void PopulateGridBooks()
{
dataGridView1.Rows.Clear();
using (OleDbConnection connect = new OleDbConnection(ConfigurationManager.ConnectionStrings["LibrarieConectare"].ConnectionString))
{
OleDbCommand command = connect.CreateCommand();
command.Parameters.AddWithValue("#titlu", cautaTitlu.Text);
command.CommandText =
" SELECT Carti.IDCarte, Carti.Titlu, Carti.Editie, Carti.An, Carti.ISBN, Carti.Nota, Carti.IDAutor, Carti.Stoc, Edituri.NumeEditura " +
" FROM (Carti INNER JOIN Edituri ON Carti.IDEditura = Edituri.IDEditura) " +
" WHERE Titlu LIKE '%#titlu%'";
try
{
connect.Open();
OleDbDataReader dr = command.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
dataGridView1.Rows.Add(dr["IDCarte"], dr["Titlu"], dr["NumeEditura"], dr["Stoc"]);
}
}
}
catch (Exception ex)
{
MessageBox.Show("Eroare la populare data grid carti: " + ex.Message);
}
}
}
Think I found it - your parameter is wrong, you should not have an # in the AddwithValue.
Use:
//Exclude the # in the below.
command.Parameters.AddWithValue("titlu", cautaTitlu.Text);
maybe move your parameter addition line to after the command text too.
Try this,
command.CommandText =
" SELECT Carti.IDCarte, Carti.Titlu, Carti.Editie, Carti.An, Carti.ISBN, Carti.Nota, Carti.IDAutor, Carti.Stoc, Edituri.NumeEditura " +
" FROM Carti INNER JOIN Edituri ON Carti.IDEditura = Edituri.IDEditura " +
" WHERE Titlu LIKE '%' + #titlu + '%';
I suggest change in where clause as the following:
"WHERE Titlu LIKE '%' + #titlu + '%'"
Related
the code is below and the error starting from sqlCommand cmd the 13th line of this code
private void button2_Click(object sender, EventArgs e)
{
if (StudenUsn.Text == "" )
{
MessageBox.Show("Enter The Student Number");
} else {
Con.Open();
String query = "update Student_tbl set StdName='" + StudName.Text + "',where FatherName='" + FtName.Text + "',where MotherName='" + MtName.Text + "',where StdAddress='" + Address.Text + "',where Collage ='" + Collage.Text + "'set StdRoom = " + StRmNum.SelectedValue.ToString()+",StdStatus = '"+ StudSt.SelectedItem.ToString() + "' where StdUsn ='"+StudenUsn+ "')";
SqlCommand cmd = new SqlCommand(query, Con);
cmd.ExecuteNonQuery();
MessageBox.Show("Room Successfully Updates");
Con.Close();
FillStudentDGV();
}
}
Your code should look more like:
private void button2_Click(object sender, EventArgs e)
{
if (StudenUsn.Text == "" )
{
MessageBox.Show("Enter The Student Number");
} else {
var query = #"
update Student_tbl
set
StdName=#sn,
FatherName=#fn,
MotherName=#mn,
StdAddress=#sa,
Collage=#c,
StdRoom=#sr,
StdStatus=#ss
where
StdUsn=#su";
using var con = new SqlConnection(YOUR_CONN_STR_HERE);
using var cmd = new SqlCommand(query, con);
cmd.Parameters.AddWithValue(#sn, StudName.Text);
cmd.Parameters.AddWithValue(#fn, FtName.Text);
cmd.Parameters.AddWithValue(#mn, MtName.Text);
cmd.Parameters.AddWithValue(#sa, Address.Text);
cmd.Parameters.AddWithValue(#c, Collage.Text);
cmd.Parameters.AddWithValue(#sr, StRmNum.SelectedValue);
cmd.Parameters.AddWithValue(#ss, StudSt.SelectedItem);
cmd.Parameters.AddWithValue(#su, StudenUsn);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Room Successfully Updates");
FillStudentDGV();
}
}
There are good reasons to avoid using AddWithValue if you use SQLServer which you can get into at a later date if you want, but it's convenient for me (who doesn't know the types and widths of your columns) dealing with the current massive elephant in the room which is your SQL is massively vulnerable to a hacking technique known as sql injection (and to a lesser extent it would blow up with an error for any student whose name included an apostrophe) - using AddWithValue might make your query slightly slower, but better that than it be the cause of the next data breach; learn how to write SQLs right, right now
Never ever take data supplied by a user and concatenate it into an SQL string. Doing so essentially, in most cases, gives the user access to your database. So many big companies whose developers should know better, put up expensive firewalls and security and then let anyone in via this back door anyway; sql injection prone systems are one of the leading causes of hacks in the world today
Always use #parameter placeholders in the SQL for user data and add a parameter to the command's parameters collection, containing the data
Now on the topic of your actual error; the pattern for an update is
update table
set col1=#param1, col2=#param2 ...
where (some conditions)
You have one where and one set. If there is some conditional aspect to your set, like you only want to update the student name/address if it is currently null then you can do like:
update table
set
name=case when name is null then #n else name end,
address=case when address is null then #a else address end
where (some conditions)
Or more simply
update table
set
name=coalesce(name, #n)
address=coalesce(address, #a)
where (some conditions)
You can't mix n match and say "where this=that where this2=that2 set this3=that3" - that's a syntax error. Where is for picking the row you want to update and set is for starting a block of commas separated columns and values the row data is to be updated to.
Strive to write your sql nicely formatted inside an #string; it's a programming language all of its own, and will be easier to debug if it's laid out nicely
Can u try with it ?
String query = "update Student_tbl set StdName='" + StudName.Text + "',StdRoom = '" + StRmNum.SelectedValue.ToString()+"',StdStatus = '"+ StudSt.SelectedItem.ToString() + "' where FatherName='" + FtName.Text + "' and MotherName='" + MtName.Text + "' and StdAddress='" + Address.Text + "' and Collage ='" + Collage.Text + "' and StdUsn ='"+StudenUsn+ "'";
I'm trying to add a record to a table with data used from a form. My code looks like this:
private void button4_Click(object sender, EventArgs e)
{
using (SqlConnection connect = new SqlConnection(#"Data Source=(LocalDB)\v11.0;" +
#"AttachDbFilename=C:\Development\C-Sharp\LockItUp\Lockitup.mdf;Integrated Security=True"))
{
string theVault = #lblVault.Text.Replace(#"\", #"\\");
string stmt = #"INSERT INTO Users (username,password,folderloc,fullname,email,cellphone)" +
" VALUES ('" + txtUsrName.Text + "', '" + txtUserPassword.Text + "', '" + theVault + "', '" +
txtFullname.Text + "', '" + txtEmail.Text + "', '" + txtCellPhone.Text + "')";
using(SqlCommand cmd = new SqlCommand(stmt, connect))
{
try
{
connect.Open();
cmd.ExecuteNonQuery();
connect.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex);
return;
}
}
PanelSwitch("Home");
RefreshMenu();
}
}
However, every time run it, I get the error message 'String or binary data would be truncated.' I pin pointed the error to the folderloc field. A directory goes in it. I'm currently trying to put the value C:\Development\locker in it, but I keep getting the error. How can I resolve this problem?
You've got several issues with your code. First, to address the error you are receiving String or binary data would be truncated. The reason for this is that the field in the table isn't big enough to store the data. Go into your database and look at the Users table and look at each field and make sure the field is defined with enough width to store the data (e.g., look for VARCHAR(20) or something and change it to something like VARCHAR(500)).
Secondly, as #David suggested, you need to address your issue of SQL Injection. You are directly inserting dynamic values into your SQL statement. This is bad news. Microsoft has a good article on this subject and how to avoid it.
Thirdly, you should not store your passwords as plain text. They should be salted and hashed. Look at this article for a good tutorial on this.
I want to update data in my SQL Server table, this code here works fine in my other project but when I copied it to other project it doesn't work anymore.
Here's my code:
con.Open();
float prc = float.Parse(textBox4.Text);
int sum = int.Parse(textBox3.Text);
string sql = "UPDATE LIB_INVENTORY set PRICE=(" + prc + "), QUANTITY=([QUANTITY]) +
(" + sum + "), BSTATUS='" + textBox5.Text + "' where BOOKNAME='"
+ textBox1.Text + "' and PUBLISHER='" + textBox2.Text + "'";
SqlCommand cmd = new SqlCommand(sql, con);
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("One item updated updated!");
It runs successfully but when I checked the table no data has been successfully updated. I checked my code but it is really the same as my other project that works fine. Can somebody help me?
if no error is there then it means where clause is not fulfilling. i think your has typed like :
where BOOKNAME='"<spaace>+ textBox1.Text+<spaace>"' and PUBLISHER='"<spaace>+ textBox2.Text +<spaace>"'";
so just erase space and
try this out.
string sql = "UPDATE LIB_INVENTORY set PRICE=("+prc+"), QUANTITY= ([QUANTITY]) + ("+sum+"), BSTATUS='"+textBox5.Text+"' where BOOKNAME='"+textBox1.Text+"' and PUBLISHER='"+textBox2.Text+"'";
as suggested you should really use parameters for your sql query. On top of this do the following :
SqlCommand cmd = new SqlCommand(sql, con);
int nbrUpdates = cmd.ExecuteNonQuery();
con.Close();
if (nbrUpdates>0) MessageBox.Show("One item updated updated!");
else MessageBox.Show(sql);
You can then check if the string in the sql is correct.
Also log in to your database manually and check if the data you want to update is in fact there.
If it is and the update still does not work, make your code do a select statement for the data you want to update. You still might be accessing the wrong database.
Now to start using sql with parameters like you are supposed to read this :
http://www.csharp-station.com/Tutorial/AdoDotNet/lesson06
Ok, So i am trying to write a program for my HP Ipaq211 that I can use at work (I am a server) to take orders, as opposed to using paper. I have gotten pretty far and decided that it would be best to use a database to hold the full menu information. I created a database for drinks to start with 4 Columns {ID, Item, Price, Options} where ID is the primary Key.
I created a few concoctions that allow me to read the data into an object, and then create a list of those said objects, but all of them perform really slow (4 sec ish on the Ipaq). I have taught myself everything I know in terms of programming so bear with me, here is one of my attempts (which works but is slow and i need it to work faster!)
public class _itemObject
{
public _itemObject()
{
ID = 0;
_ioName = "";
_ioPrice = "";
_ioOptions = -1;
}
public _itemObject(int _next, string Tbl_Name)
{
try
{
string conSTR = "Data Source=" + (System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase)) +
"\\TestDatabase.sdf;Persist Security Info=True";
SqlCeConnection _connection = new SqlCeConnection(conSTR);
SqlCeCommand _cmd = new SqlCeCommand("select ID from " + Tbl_Name + " where ID ='" + _next.ToString() + "'", _connection);
SqlCeCommand _cmd2 = new SqlCeCommand("select * from " + Tbl_Name + " where ID ='" + _next.ToString() + "'", _connection);
SqlCeCommand _cmd3 = new SqlCeCommand("select price from " + Tbl_Name + " where ID ='" + _next.ToString() + "'", _connection);
SqlCeCommand _cmd4 = new SqlCeCommand("select special from " + Tbl_Name + " where ID ='" + _next.ToString() + "'", _connection);
_connection.Open();
if (_cmd.ExecuteScalar() != null)
{
ID = (Convert.ToInt32(_cmd.ExecuteScalar().ToString()));
_ioName = _cmd2.ExecuteScalar().ToString();
_ioPrice = _cmd3.ExecuteScalar().ToString();
_ioOptions = (Convert.ToInt32(_cmd4.ExecuteScalar().ToString()));
}
else
{
}
_connection.Close();
}
finally
{
}
}
this object is then added to a List<_itemObject> where I load any needed data from.
I know it is ugly but if anyone has any lessons for me I would appreciate it :)
The answer may differ on what is your final goal.
a) why do you need to use 4 sql commands? One command should be OK to get all information. In example:
SELECT * FROM table_name;
will report all data at once within a SqlCeDataReader.ExecuteReader() call that you can iterate to fill a list.
b) if no SQL server will be invoked later (for remote access/sync etc) and if not too much data records, you may consider switching to another data storage (ie xml (slow too) or binary file).
please provide more details if you need more help.
There are also SQLCE examples available here in stackoverflow: Local database, I need some examples and others (use search).
OK, from your comments I see you have some issues getting started?!
At http://www.codeproject.com/Articles/310378/A-Restaurant-and-Waiter-helper-app-in-WPF-and-Wind you will find a complete POS solution. You can change the waiter's code to use a local database.
...maybe adding some simple example later...
I am trying to update a mysql table while inside a c# for loop and a if statement well a few if statements. While running with a break point it will run the executenonquery once but the next loop it does not hit that. Even when i does hit the nonquery it does not change the table information.
the ffi string is the name of the column in my table and string val is what i want to put in. I know this is not the safe way to do it but I will change it when i can get it working the way it should.
Updated code it now runs the NONQUERY every time it should but still not updating the table
Code:
for (a = 0; a <= z; a++)
{
if (ds3.Tables[0].Rows[a][1].ToString() == dataGridView1.Rows[i].Cells[0].Value.ToString())
{
if (ds3.Tables[0].Rows[a][2].ToString() == dataGridView1.Rows[i].Cells[1].Value.ToString())
{
if (ds3.Tables[0].Rows[a][3].ToString() == dataGridView1.Rows[i].Cells[2].Value.ToString())
{
MessageBox.Show("We have a match " + dataGridView1.Rows[i].Cells[0].Value.ToString() + " " + dataGridView1.Rows[i].Cells[1].Value.ToString() + " " + dataGridView1.Rows[i].Cells[t].Value.ToString());
try
{
string ffi = textBox1.Text;
decimal val = decimal.Parse(dataGridView1.Rows[i].Cells[t].Value.ToString());
MySqlCommand cmd = new MySqlCommand("Update spt_results SET " + ffi + " = " + val + " where project_Id =" + dataGridView1.Rows[i].Cells[0].Value.ToString() + "",connection2);
//cmd.Connection = connection2;'
// cmd.Connection.Open();
cmd.ExecuteNonQuery();
//cmd.Connection.Close();
}
catch
{
}
The message box does show every loop and the connection2.open will run everytime
Thank you for looking and your help
The update string looks like "update spt_results SET FFI 300 = '15' where project_Id =AAA007" when it runs
Brent
Look at your code:
MySqlCommand cmd = new MySqlCommand();
cmd.CommandText = // ... snip SQL injection invitation
connection2.Open();
cmd.ExecuteNonQuery();
connection2.Close();
The MySqlCommand has no connection. You're opening and closing a connection, but it's got nothing to do with the command. I'd actually expect cmd.ExecuteNonQuery() to throw an exception because it has no connection...
Note that you should use using statements for the command and connection, to ensure that all the resources get cleaned up even in the face of an exception.
use cmd.Connection = connection2; just after connection2.Open();.
When you trying to execute the cmd.ExecuteNonQuery(), it is raising the error for no Connection bounded with the Command and error is caught in catch block. You didn't came to know because you have not doing anything in catch block for the errors.
If uncomment your code: The connection is open correctly and your code should work. But I'd suggest you to open connection once, before the loop, and close it at the end.
Another point is that you catched ALL exceptions, it is not good. The problem can be with the query, try to run "update spt_results SET FFI 300 = '15' where project_Id =AAA007" in the console or another MySQL client. It will throw an error. The field name 'FFI 300' must be quoted because it contains a white space and the value 'AAA007' must be quoted as a string literal. Try this query -
UPDATE spt_results SET `FFI 300` = '15' WHERE project_Id = 'AAA007'