Hello I am trying to do an application in C# very simple it has a search bar(textbox) and a button, my purpose is for eg when I type E1 I want to display the item from MySql. At the moment, when I type E1 I get some kind of error that says unknown column "e1". I will post my code below:
public partial class MainWindow : Window
{
MySqlConnection connection = new MySqlConnection("datasource=localhost;port=3306;username=root;password=pass;");
MySqlCommand cmd;
MySqlDataReader mdr;
private void button_Click(object sender, RoutedEventArgs e)
{
try
{
connection.Open();
string selectRaspuns = "SELECT * FROM testdb.element WHERE name="+ userInput.Text;
cmd = new MySqlCommand(selectQuery, connection);
mdr = cmd.ExecuteReader();
if (mdr.Read())
{
r1.GetDenumire(mdr.GetString("name"));
r1.GetInformatii(mdr.GetString("info"));
r1.Show();
}
else
{
MessageBox.Show("Error");
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
}
finally
{
connection.Close();
}
}
}
I want for eg when I type E1 to display from my mySql db information's about E1 that is stored in table element column name and info can you point me what am i doing wrong ?Thanks
The problem is in this line of code:
string selectRaspuns = "SELECT * FROM testdb.element WHERE name="+ userInput.Text;
When you concatenate your input of "E1", the result is:
SELECT * FROM testdb.element WHERE name=E1
Since your string is not quoted, MySql interprets it as a column name, thus you get the "invalid column name" error.
At the very minimum, you must add quotes, like so:
string selectRaspuns = "SELECT * FROM testdb.element WHERE name='" + userInput.Text + "'";
By doing this, your resulting SQL is:
SELECT * FROM testdb.element WHERE name='E1'
and MySql will interpret "E1" as a string, which is what you intend.
That said, creating SQL using string concatenation is a bad practice and can lead to SQL injection vulnerabilities. Once you have it working as desired, I strongly urge you to circle back and replace the string concatenation with parameterized queries.
Related
When I try out this query
select Category,ItemName,ItemBrand,ItemLocation,Qty,Date ,+'0000'+convert (varchar, ItemId)
as testing from Inventory in my SSMS . It works fine.
When I use the query in c# window form it will show error
Error Unable to cast object of type 'System.Int32' to type 'System. String'
private void databaseLoading()
{
query = "select Category,ItemName,ItemBrand,ItemLocation,Qty,Date ,+'0000'+convert (varchar, ItemId) as testing from Inventory";
//query = "select * from Inventory";
exeQuery = new SqlCommand(query, sqlconn);
try
{
sqlconn.Open();
// must close after use and less memory use
sqlReader = exeQuery.ExecuteReader();
while (sqlReader.Read())
{
string Catg = sqlReader.GetString(1).ToString();
string Name = sqlReader.GetString(2).ToString();
string Brand = sqlReader.GetString(3).ToString();
string location = sqlReader.GetString(4).ToString();
cbxCatg.Items.Add(Catg);
cbxItemName.Items.Add(Name);
cbxBrand.Items.Add(Brand);
cbxLocation.Items.Add(location);
}
sqlconn.Close();
sqlconn.Open();
// dataadapter it may auto close connection but it need more memory cause it will load all information to the table
sqlAdp = new SqlDataAdapter(exeQuery);
sqlAdp.Fill(dt);
dgvInventory.DataSource = dt;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
If a type of a column in sql server is int, then you should use GetInt32() in the reader, not GetString().
In addition, your first select item is a category query = "select Category, so in the reader the string Catg must have index 0 GetString(0)
One of your database column might be int.
Use:
sqlReader.GetInt32(1).ToString()
instead
I got a problem with my C#, whenever i try to save new data in the database coming from serial comm an error comes out and says
Incorrect Syntax Near '/'
I tried every suggestion everyone gave but it just wont stop..Here it is the piece of code where it comes out.
private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
SqlConnection cn = new SqlConnection(global::test_new.Properties.Settings.Default.Database3ConnectionString);
try
{
string sql = "INSERT INTO PowerData (Date/Time,Power(W)) values(" + this.powerTextBox.Text + ",'" + this.powerTextBox.Text + "'");
SqlCommand exeSql = new SqlCommand(sql, cn);
cn.Open();
exeSql.ExecuteNonQuery();
this.powerDataTableAdapter.Fill(this.database3DataSet.PowerData);
}
catch (Exception ex)
{
}
}
You need to escape special characters in table and column names like /
INSERT INTO PowerData ([Date/Time], Power(W)) values ...
In MySQL use backticks to escape, in MSSQL use brackets.
You've got some crazy column names there. If you want to include special characters in column names like that then you must wrap them in brackets in SQL, e.g. [Date/Time]. A better idea would be to not use such characters in the first place.
syntax should be like below, escape all columns with special characters
INSERT INTO PowerData
([Date/Time], [Power(W)])
VALUES
(GETDATE(), 'test1')
DEMO
First, "this.powerTextBox.Text" - I am guessing this shouldn't be the same value for both variables
change your code to this:
DateTime dt = DateTime.Parse(this.powerTextBox.Text);
string PowerW = this.powerTextBox.Text;
string sql = "INSERT INTO PowerData ([Date/Time],[Power(W)]) values(#val1, #val2);"
SqlCommand exeSql = new SqlCommand(sql, cn);
exeSql.Parameters.AddWithValue("#val1", dt);
exeSql.Parameters.AddWithValue("#val2", PowerW);
cn.Open();
exeSql.ExecuteNonQuery();
I'm trying to filter-search the data from a GridView control which is bound to a SQL data connection but i'm not having any success. Whenever I try to search for something, it results in no records found. Here is my main searching code:
public void FilterGridView(string column, string terms) //SELECT * FROM [Table_1] WHERE [First Name] LIKE '%valuetosearchfor%' is the format to use here
{
DataTable filterTable = new DataTable(); //create a datatable to hold the data while we retrieve it
SqlConnection connection = new SqlConnection("Data Source=TAMUWINPART\\SQLEXPRESS;Initial Catalog=phpMyWorkers;Integrated Security=True"); //connect to SQL
try
{
connection.Open(); //open the connection
string filterStatement = "SELECT * FROM [Table_1] WHERE #column LIKE '%#terms%'"; //select all from table_1 with the correct column name / terms
SqlCommand sqlCmd = new SqlCommand(filterStatement, connection); //make a sql command
sqlCmd.CommandType = CommandType.Text; //make it an average joe sql text command
//define the # sql variables
sqlCmd.Parameters.AddWithValue("#column", column);
sqlCmd.Parameters.AddWithValue("#terms", terms);
SqlDataAdapter filterAdapter = new SqlDataAdapter(sqlCmd); //make a data adapter to get all the data from the command and put it into the data table
filterAdapter.Fill(filterTable); //fill the data table with the data from the SQL connection
if(filterTable.Rows.Count > 0) //if records were found relating to the terms
{
//if records WERE found
workersView.DataSource = filterTable; //set the data source to this instead
workersView.DataBind(); //refresh the data
}
else
{
//no records were found in this case, do not be an inneficient guy who will refresh the gridview for no reason
FilterSearchTerms.Text = "0 Records Found!"; //notify the user that he/she won't get anything
}
}
catch (System.Data.SqlClient.SqlException ex) //if the thing just decides that it doesn't want to work today
{
string msg = "myWorkers had a problem fetching the data : ";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
connection.Close(); //close the connection
}
}
public void FilterSearchButton_Click(object sender, EventArgs e) //when someone clicks the button to filtersearch the gridviews
{
string column = FilterSearchDropdown.SelectedValue.ToString(); //get the column that the user wants to filter by and make sure it's a string
string terms = FilterSearchTerms.Text; //get the terms to search by - verified string for sure
FilterGridView(column, terms);
}
public void FilterRemoveButton_Click(object sender, EventArgs e) //when someone decides to remove the filter
{
BindGridView(); //refresh the gridview based on all of the data
FilterSearchTerms.Text = ""; //remove the text from the filter search terms box
}
Here is a picture of what the layout looks like.
Even if I search for real data it results in this being called
else
{
//no records were found in this case, do not be an inneficient guy who will refresh the gridview for no reason
FilterSearchTerms.Text = "0 Records Found!"; //notify the user that he/she won't get anything
}
meaning that the datatable's row count is 0...
Does anyone know why? Thank you.
I suspect that your SQL LIKE code is incorrect. Take a look at how to use like with SQL parameter in this question:how-to-get-like-clause-to-work-in-ado-net-and-sql-server. It would also help to display the final sql command text that gets sent to the database.
Replace this line :
string column = FilterSearchDropdown.SelectedValue.ToString();
with this:
string column = FilterSearchDropdown.SelectedText;
Also, you need correct your command string and command parameters as Emmad Kareem suggested in other answer. Your string and parameter should be like below:
string filterStatement = "SELECT * FROM [Table_1] WHERE [{0}] LIKE #terms"; //select all from table_1 with the correct column name / terms
filterStatement = string.Format(filterStatement, column);
.... .... .... .... .... ....
// sqlCmd.Parameters.AddWithValue("#column", column );
sqlCmd.Parameters.AddWithValue("#terms", "%" + terms + "%");
You only need to replace this query:
string filterStatement = "SELECT * FROM [Table_1] WHERE #column LIKE '%"+terms+"%'";
And you should be able to find your data.
Hi there its the first time to use stackoverflow so hi every one L)
i'm a beginner into C# forms i take it as a fun hobby.
SqlCommand comm = new SqlCommand("SELECT COUNT(*) FROM Members where sponser = "
+textbox1.text+"'", connection);
Int32 count = (Int32)comm.ExecuteScalar();
textbox2.Text ="Found "+ count+" Members;
well its just a mix between 2 codes i have got from google xD
how ever the error appear here textbox2.Text ="Found "+ count+" Members;
There are a couple of things wrong with this line of code:
textbox2.Text ="Found "+ count+" Members;
First of all, there's a syntax error. You never close the second set of quotes. You'd do so like this:
textbox2.Text ="Found "+ count+" Members";
However, string concatenation like this is still a little messy. You have two literal strings and you're trying to add them to an integer, which isn't entirely intuitive (and probably slower than it needs to be). Instead, consider using a formatting string:
textbox2.Text = string.Format("Found {0} Members", count);
This will take the value from count (which is an integer) and, internally to the string.Format() function, discern its string representation and insert it into the placeholder in the formatted string.
UPDATE: That takes care of the compile-time errors. Now you're going to get a run-time error from this:
SqlCommand comm = new SqlCommand("SELECT COUNT(*) FROM Members where sponser = "
+textbox1.text+"'", connection);
As soon as you try to execute that SQL statement you're going to get an error from the database because the resulting query has a syntax error:
SELECT COUNT(*) FROM Members where sponser = some text'
You're missing the opening single-quote for the parameter. Something like this:
SqlCommand comm = new SqlCommand("SELECT COUNT(*) FROM Members where sponser = '"
+textbox1.text+"'", connection);
However, and this is important, you're still not done. This line of code is wide open to a very common and easily exploitable vulnerability called SQL Injection. You'll want to move away from direct string concatenation and use parameters for your SQL queries. Something like this:
SqlCommand cmd = new SqlCommand("SELECT COUNT(*) FROM Members where sponser = #sponser");
cmd.Parameters.Add("#sponser", textbox1.text);
Int32 count = (Int32)comm.ExecuteScalar();
Know that there is still a lot more you can do to improve this, which is all worth learning over time. Things you can look into are:
Checking and validating user input (textbox1.text) before you even try to use it in a SQL query.
Checking the output of comm.ExecuteScalar() before trying to directly cast it to an Int32 (this would give you a runtime error if it returns anything other than an integer for some reason).
Consider using something like Linq to Sql in place of ADO.NET components as it does a lot more for you with less code on your part.
protected void Page_Load(object sender, EventArgs e)
{
lb1.Text = GetRecordCount(textbox2.Text).ToString();
}
private int GetRecordCount(string myParameter)
{
string connectionString = ConfigurationManager.ConnectionStrings["DBConnection"].ToString();
Int32 count = 0;
string sql = "SELECT COUNT(*) FROM members WHERE sponsor = #Sponsor";
using (SqlConnection conn = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.Add("#Sponsor", SqlDbType.VarChar);
cmd.Parameters["#Sponsor"].Value = myParameter;
try
{
conn.Open();
count = (Int32)cmd.ExecuteScalar();
}
catch (Exception ex)
{
}
}
return (int)count;
}
You are missing a closing " at the end:
textbox2.Text ="Found "+ count+" Members";
You code is vulnerable to SQL Injections. Please consider using Parameters.
private int GetMemberCount(string connectionString, string sponsor)
{
using(var connection = new SqlConnection(connectionString))
using(var command = connection.CreateCommand())
{
command.CommandText = "SELECT COUNT(*) FROM members WHERE sponsor = #Sponsor";
command.Parameters.AddWithValue("#Sponsor", sponsor);
return Convert.ToInt32(command.ExecuteScalar());
}
}
//Usage
var sponsor = textbox1.text;
var count = GetMemberCount(connectionString, sponsor);
textbox2.Text = string.Format("Found {0} Members", count);
I've been working on a delete function for a while now, and I cannot get past this error.
Delete Failed ORA-00904 "SYSTEM"."DATA"."DATAROWVIEW": invalid identifier
private void button3_Click(object sender, EventArgs e)
{
string yesNoPrompt = "Are you sure you want to delete this patient?";
const string caption = "";
var result = MessageBox.Show(yesNoPrompt, caption,
MessageBoxButtons.YesNo,
MessageBoxIcon.Question);
if (result == DialogResult.Yes)
{
string sql = "DELETE FROM CLIENT WHERE (CLI_LNAME =" + listBox1.SelectedItem.ToString() + ")" ;
try
{
string connectionString = GetConnectionString();
using (OracleConnection connection = new OracleConnection())
{
connection.ConnectionString = connectionString;
connection.Open();
OracleCommand command = new OracleCommand(sql, connection);
command.CommandType = CommandType.Text;
command.ExecuteNonQuery();
}
}
catch (System.Data.OracleClient.OracleException ex)
{
MessageBox.Show("Delete Failed" + ex.Message);
}
}
}
The table in the database is CLIENT and I am trying to find a specific person by their last name, or CLI_LNAME. I don't think the problem is in the name being passed, but more of how it is being passed.
Any ideas?
Your query gets translated to
DELETE FROM CLIENT WHERE (CLI_LNAME = SYSTEM.DATA.DATAROWVIEW)
Due to the missing single quotes and hence its trying to find a column named SYSTEM.DATA.DATAROWVIEW which is not present in the Client table. hence the error.
When you use single quotes then its looking for the text in that particular column
DELETE FROM CLIENT WHERE (CLI_LNAME = 'PatientName') // Now its not a column as such
Use Parameterized queries to avoid SQL injection
Looks like listBox1.SelectedItem.ToString() returns "SYSTEM"."DATA"."DATAROWVIEW". You probably want to access a specific item of the DataRowView that's the SelectedItem, not the entire DataRowView object itself. Maybe listBox1.SelectedItem[0].ToString() is what you want?.
Also you have to add quotes as #Habib.OSU mentions.
And the obligatory sql injection warning: Don't concatenate user inputs into SQL string. It opens up for SQL injection attacks. Use parameterized queries.
you are missing single quote in parameters
string sql = "DELETE FROM CLIENT WHERE (CLI_LNAME ='" + listBox1.SelectedItem.ToString() + "')" ;
Its better if you could use Parameterized query