C# Sql Column name is not valid - c#

private void button4_Click_1(object sender, EventArgs e)
{
string s = textBox1.Text;
string s1 = comboBox1.Text;
string s2 = comboBox2.Text;
SqlCeConnection conn = new SqlCeConnection(#"Data Source=D:\Desktop\DB2\DB2\Database1.sdf");
try
{
conn.Open();
SqlCeCommand cmd = new SqlCeCommand(" update Kambariai set Klientas=[s] Where [Kambario rūšis]=[s1] ", conn);
cmd.ExecuteNonQuery();
toolStripStatusLabel1.Text = "Duomenys įrašyti";
conn.Close();
}
catch (Exception ee)
{
MessageBox.Show(ee.Message);
}
}
I am trying to update my datatable by updating Klientas value with textbox1.Text which is made to string = s. It should work fine as Sql But I get an error saying that The column name is not valid Column = s1. s1 shouldn't be targeted as column name it should be used as column row value.
This is outdated image Kliento ID is changed to Klientas

Try this:
SqlCeCommand cmd = new SqlCeCommand("update Kambariai set Klientas="+s+" Where [Kambario rūšis]='"+s1+"' ", conn);
Analysis:
From what you have tried, cmd has value like :
update Kambariai set Klientas=s Where [Kambario rūšis]=s1
From by putting proper double and single quotes around it, the value would be like:
update Kambariai set Klientas=1 Where [Kambario rūšis]='bar'
Side Note:
I would not recommend this method since it increases the risk of SQL injection. Use parameterized query instead.

Try This :
SqlCeCommand cmd = new SqlCeCommand(" update Kambariai set Klientas='" + s +"' Where [Kambario rūšis]='" + s1 + "'", conn);

Related

How to put the autoincrement value in textbox

private void button1_Click(object sender, EventArgs e)
{
String path = "Data Source=LOCALHOST; Initial Catalog= system; username=root; password=''";
MySqlConnection sqlconn = new MySqlConnection(path); //communicator //constructors
MySqlCommand sqlcomm = new MySqlCommand();
sqlconn.Open();
sqlcomm.CommandType = CommandType.Text;
sqlcomm.Connection = sqlconn;
sqlcomm.CommandText = "INSERT INTO maica (Lastname) VALUES ('" + textBox2.Text + "')";
sqlcomm.ExecuteNonQuery();
sqlconn.Close();
MessageBox.Show("Record saved");
}
This is a code in the add button. In phpmyadmin, I checked the autoincrement box. Whenever I run the form, I left the textBox1 which is the ID empty and I input a name in textBox2 which is the Lastname. In phpmyadmin, the ID autoincrements. The textbox1 should have a value of 0001 before I click the add button then after I click the add button, the textBox1 should have 0002. How do I put the autoincrement value in textBox1?This is in winform c#. Sorry for the bad english TIA.
If your database has an ID column with AUTO_INCREMENT set, you do not need to pass a value for the ID into the SQL Insert Statement. You can simply do:
sqlcomm.CommandText = "INSERT INTO maica (Lastname) VALUES ('" + textBox2.Text + ')";
It is also better to use SqlCommand instead of string concatenation as it is protects against SQL Injection and also deals with Type and formatting issues.
That's the query you need to run together with the insert.
SELECT LAST_INSERT_ID();
Here's some code to get the ID, first declare a global String somewhere in the class like that
private String entryIdString;
then
public int insertGetEntryID()
{
String sqlquery = "INSERT INTO maica (Lastname) VALUES ('" + textBox2.Text + "'); SELECT LAST_INSERT_ID();";
SqlCommand command = new SqlCommand(sqlquery, sqlconn);
try
{
sqlconn.Open();
entryIdStr = command.ExecuteScalar().ToString();
return int.Parse(entryIdStr);
}
catch (Exception ex)
{
Console.WriteLine("Exception in DBHandler", ex);
return -1;
}
finally
{
sqlconn.Close();
}
}
This method returns an integer holding the last ID in your table. Now you just set the value to textBox1
textBox1.Text = "ID: " + getEntryID();
or if you want just the ID
textBox1.Text = "" + getEntryID();
I was also just about to tell you what Gideon said about you inserting an ID (when if it's set to autoincrement in the DB, you don't need to).

WPF - Datagrid filter by Name with textBox

I'm using this code to filter my dataGrid with a textBox, it works fine for filtering by the Id, but if I changed it to filter by the Name ( i just change the "Id" in the query with "Name"), it doesn't work, something like "Column name "Entered text" is invalid. This same error occurs when the query is set for Id and you enter a letter, apparently it only works with numbers.
Here is the code:
private void textBox_TextChanged(object sender, TextChangedEventArgs e)
{
try {
SqlConnection con = new SqlConnection(#"Data Source =.\SQLEXPRESS; AttachDbFilename = C:\Users\Sione\Documents\AcademiaSQLDB.mdf; Integrated Security = True; Connect Timeout = 30; User Instance = True");
con.Open();
string query = "select * from instrutor";
if (textBox.Text != "") // Note: txt_Search is the TextBox..
{
query += " where Nome =" + textBox.Text;
}
SqlCommand cmd = new SqlCommand(query, con);
cmd.ExecuteNonQuery();
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataTable dt = new DataTable("instrutor");
adp.Fill(dt);
instrutorDataGrid.ItemsSource = dt.DefaultView;
adp.Update(dt);
con.Close();
} catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
So how can I filter the dataGrid by the Name? Filtering by the Id works perfect thought but it's not very user friendly. Thanks
You need to wrap your filter with '
So the line :
query += " where Nome =" + textBox.Text;
become
query += " where Nome ='" + textBox.Text + "'";
Note that this is a quick fix, and you need to consider #Dennis answer
Don't use string concatenation to build SQL queries, this will lead to SQL injections. Use parameters instead:
private SqlCommand CreateCommand(SqlConnection connection)
{
return new SqlCommand("select * from instrutor", connection);
}
private SqlCommand CreateCommand(SqlConnection connection, TextBox textBox)
{
var command = new SqlCommand("select * from instrutor where Nome = #nome",
connection);
command.Parameters.AddWithValue("#nome", textBox.text);
return command;
}
private void textBox_TextChanged(object sender, TextChangedEventArgs e)
{
// ...
using (var command = !string.IsNullOrEmpty(textBox.Text) ?
CreateCommand(conn, textBox) : CreateCommand(conn))
{
// ...
}
// ...
}
Also note, that: 1) SqlConnection, SqlCommand, SqlDataAdapter implement IDisposable and should be disposed (see this); 2) there's no need to execute cmd.ExecuteNonQuery();.

Delete & Update query doesn't work in ADO.NET

I am trying to DELETE a record of Access Database using OleDbCommand class of Connected Architecture
using System.Data.OleDb;
using System.Data;
protected void Button2_Click(object sender, EventArgs e)
{
String x = "Connection String...";
OleDbConnection con = new OleDbConnection(x);
con.Open();
String query = "Delete FROM TB WHERE NO=#number";
OleDbCommand cmd = new OleDbCommand(query, con);
cmd.Parameters.AddWithValue("#number", TextBox2.Text);
int res = cmd.ExecuteNonQuery();
if (res > 0)
{
Label.Text = "Deleted successfully";
}
else
{
Label.Text = "Not Deleted";
}
con.Close();
}
Every time I try deleting record Else Condition is executed which is NOT DELETED.
Same problem with UPDATE query,
protected void Button3_Click(object sender, EventArgs e)
{
String x = "Connection String..";
OleDbConnection con = new OleDbConnection(x);
con.Open();
String query = "UPDATE TB SET NM = #name WHERE NO = #TextBox_NO";
OleDbCommand cmd = new OleDbCommand(query, con);
int res = cmd.ExecuteNonQuery();
if (res > 0)
{
Label.Text = "Updated successfully";
}
else
{
Label.Text = "Not Updated";
}
con.Close();
}
INSERT query works perfectly fine.
Where am I doing wrong?
Preface: I know nothing of ASP.NET but I do know MS Access. And NO is a reserved word. Hence, if reserved words are used may result in unexpected answers or errors when referenced as fields.
To resolve, consider bracketing the NO column in both delete and update queries.
String query = "DELETE FROM TB WHERE [NO] = #number"
String query = "UPDATE TB SET NM = #name WHERE [NO] = #TextBox_NO"
I can confirm this solution as I just tested a NO vs [NO] column reference in a SQL query in MS Access 2013. The former returned zero records but latter returned correct records.
i think there is any datatype conversion error, that's why it's not deleting, and for the update case you just missed the parameter to pass #name,#TextBox_No
See here Why to use Add()
You need to change parameter passing method AddedWithValue() to Add()
Delete:
String query = "Delete FROM TB WHERE NO=#number";
OleDbCommand cmd = new OleDbCommand(query, con);
cmd.Parameters.Add("#number", OleDbType.Numeric, 30).Value=TextBox2.Text;
int res = cmd.ExecuteNonQuery();
if (res > 0)
{
Label.Text = "Deleted successfully";
}
else
{
Label.Text = "Not Deleted";
}
con.Close();
and for Update u missed the parameter to pass:
String x = "Connection String..";
OleDbConnection con = new OleDbConnection(x);
con.Open();
String query = "UPDATE TB SET NM = #name WHERE NO = #TextBox_NO";
OleDbCommand cmd = new OleDbCommand(query, con);
cmd.Parameters.Add("#name ", OleDbType.VarChar, 200).Value=your_Name_Variable;//
cmd.Parameters.Add("#TextBox_NO", OleDbType.Numeric, 30).Value=Your_No_Variable;
int res = cmd.ExecuteNonQuery();
if (res > 0)
{
Label.Text = "Updated successfully";
}
else
{
Label.Text = "Not Updated";
}
con.Close();
If it's not deleting any record that means int res = cmd.ExecuteNonQuery(); is returning 0 or no records deleted. Make sure that the condition in your WHERE clause WHERE NO=#number matches any record. To validate run a select along the line with the same condition
SELECT 1 FROM TB WHERE NO=#number
Also, try trimming the textbox data before punching as parameter like
cmd.Parameters.AddWithValue("#number", TextBox2.Text.Trim());
If NO is of type INT then covert it to integer before passing as parameter like
cmd.Parameters.AddWithValue("#number", Convert.ToInt32(TextBox2.Text.Trim()));
You can follow the same rules for your UPDATE case as well. Also, I don't see you are passing any parameter for your UPDATE query. Did you just skipped that in posted code?
String query = "UPDATE TB SET NM = #name WHERE NO = #TextBox_NO";
OleDbCommand cmd = new OleDbCommand(query, con);

update data in access database using name two column

update data in access database using name two column
because one column have same data because SerialNumber and Start can be Repeat
that's make update in all row have same data
i use this code but i have syntax Error
private void button3_Click(object sender, EventArgs e)
{
try
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
string query = "update Timer set Stop='" + label1.Text + "'where (SerialNumber,Start)='" + comboBox1.Text + "','" + textBox1.Text + "' ";
command.CommandText = query;
command.ExecuteNonQuery();
MessageBox.Show("Data saved");
connection.Close();
send_data f2 = new send_data(comboBox1.Text,label2.Text);
f2.ShowDialog();
}
catch (Exception ex)
{
MessageBox.Show("ERORR" + ex);
}
}
The correct syntax for the WHERE clause is
WHERE fieldname operator value AND/OR fieldname operator value ....
So the correct way to update that record is
string query = #"update Timer set Stop=? where SerialNumber = ? AND Start = ?";
command.CommandText = query;
command.Parameters.AddWithValue("#p1", label1.Text);
command.Parameters.AddWithValue("#p2", comboBox1.Text );
command.Parameters.AddWithValue("#p3", textBox1.Text);
command.ExecuteNonQuery();
Notice that before the WHERE keyword you need a space and I have changed your code to use a more secure parameterized approach instead of string concatenation

How to Access Specific Fields of Data from Database

I am working on a inventory software in which I want to access the ProductName and Product Price by Comparing it With the ProductCode, the Data I've Already Stored in Database table named ProductLog, the Data in Product Log is:
ItemNO Productode ProductName ProductPrice
1 123 lux 58
2 321 soap 68
now I want that I only enter productCode in my textbook named txtProductCode, and press tab then ProductPrice(txtProductPrice) and ProductName(txtProductName) boxes fills automatically.
The code I tried to compare the Productcode and access values is:
private void txtProdcutCode_Leave(object sender, EventArgs e)
{
///////////////////////////////////////////////////////////////////////
InitializeComponent();
string sql;
int productCode = 0;
productCode = Convert.ToInt32(txtProdcutCode.Text);
sql = "";
sql = "SELECT dbo.ProductLog.ProductName, dbo.ProductLog.ProductName";
sql = " WHERE ProductLog.ProductCode = " + txtProdcutCode.Text + "";
SqlConnection cn = new SqlConnection();
SqlCommand rs = new SqlCommand();
SqlDataReader sdr = null;
clsConnection clsCon = new clsConnection();
clsCon.fnc_ConnectToDB(ref cn);
rs.Connection = cn;
rs.CommandText = sql;
sdr = rs.ExecuteReader();
while (sdr.Read())
{
txtProductPrice.Text = sdr["ProductPrice"].ToString();
txtProductName.Text = sdr["ProductName"].ToString();
}
//lblTotalQuestion.Text = intQNo.ToString();
sdr.Close();
rs = null;
cn.Close();
/////////////////////////////////////////////////////////////////////////
}
but in line productCode = Convert.ToInt32(txtProdcutCode.Text); it says Input string was not in a correct format.
Please help me out with this problem.
EDIT:
I've also tried this code :
private void txtProdcutCode_Leave(object sender, EventArgs e)
{
///////////////////////////////////////////////////////////////////////
string sql;
// int productCode = 0;
//productCode = Convert.ToInt32(txtProdcutCode.Text);
sql = "";
sql = "SELECT dbo.ProductLog.ProductName, AND dbo.ProductLog.ProductName";
sql = " WHERE dbo.ProductLog.ProductCode = " + txtProdcutCode.Text + "";
SqlConnection cn = new SqlConnection();
SqlCommand rs = new SqlCommand();
SqlDataReader sdr = null;
clsConnection clsCon = new clsConnection();
clsCon.fnc_ConnectToDB(ref cn);
rs.Connection = cn;
rs.CommandText = sql;
sdr = rs.ExecuteReader();
while (sdr.Read())
{
txtProductPrice.Text = sdr["ProductPrice"].ToString();
txtProductName.Text = sdr["ProductName"].ToString();
}
//lblTotalQuestion.Text = intQNo.ToString();
sdr.Close();
rs = null;
cn.Close();
/////////////////////////////////////////////////////////////////////////
}
but it says Incorrect syntax near the keyword 'WHERE'. means I am making mistake in calling database table in my query, but I am not able to find out the mistake ...
There are some issues with your SQL.
You were originally overwriting the sql variable and only ended up with a WHERE clause;
You don't have a FROM statement so the database doesn't know where you're trying to retrieve records from.
The use of AND in a SELECT statement is incorrect; you just need commas to separate the fields.
You're never selecting ProductPrice from the DB, but selecting ProductName twice!
You're not using parameterized SQL for your query, leaving your app open to SQL injection attacks.
To address this (points 1-4, I will leave point 5 for your own research),
sql = "";
sql = "SELECT dbo.ProductLog.ProductName, AND dbo.ProductLog.ProductName";
sql = " WHERE dbo.ProductLog.ProductCode = " + txtProdcutCode.Text + "";
Should be
sql += "SELECT ProductName, ProductPrice";
sql += " FROM dbo.ProductLog";
sql += " WHERE ProductCode = '" + txtProdcutCode.Text + "'";
Note: This answer assumes that the value of txtProductCode.Text is an integer!
EDIT: It turns out that the column, ProductCode, was a VarChar. For OP
and others reading this question, when you get SQL conversion errors
check your column datatype in SQL server and make sure it matches what
you're submitting.
That's the basics. There are many other improvements that can be made but this will get you going. Brush up on basic SQL syntax, and once you get that down, look into making this query use a parameter instead of directly placing txtProductCode.Text into your query. Good luck!
Never call InitializeComponent method twice.It's creating your form and controls and it's calling in your form's constructor.Probably when you leave your textBox it's creating again and textBox will be blank.therefore you getting that error.Delete InitializeComponent from your code and try again.
Update: your command text is wrong.here you should use +=
sql += " WHERE dbo.ProductLog.ProductCode = " + txtProdcutCode.Text + "";
But this is not elegant and safe.Instead use paramatirezed queries like this:
SqlCommand cmd = new SqlCommand();
cmd.Connection = cn;
cmd.CommandText = "SELECT dbo.ProductLog.ProductName,dbo.ProductLog.ProductName WHERE dbo.ProductLog.ProductCode = #pCode";
cmd.Parameters.AddWithValue("#pCode", txtProdcutCode.Text );

Categories