try
{
string Query = "SELECT Registrations list FROM [Records] WHERE textBox = '" + comboBox.SelectedValue + "'";
OleDbConnection me = new OleDbConnection(connection);
OleDbCommand constr = new OleDbCommand(Query, me);
OleDbDataReader reader;
connection.Open();
reader = constr.ExecuteReader();
if (reader.Read())
{
OleDbParameter parameter = constr.Parameters.Add(new OleDbParameter("Registrations list", OleDbType.Integer));
textBox.Text = reader["Registrations list"].ToString();
}
me.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Im trying to get database values to display in textbox but keep getting the error, i've tried mostly everything possible
wrap the column name with square brackets
SELECT [Registrations list] FROM [Records] WHERE textBox
Otherwise sql server looks for a column called Registrations and then tries to alias it as [List]
Enclose the column name in square brackets.
SELECT [Registrations list]
If the column names contais space then you need to enclose the column name in square brackets else SQL Server will consider it as two column names and since comma will also be not present hence it will give you syntax error.
I suppose there is an error in the SQL
string Query = "SELECT Registrations list FROM [Records] WHERE textBox = '" + comboBox.SelectedValue + "'";
Between SELECT and FROM there should be a comma separated list of columns belinging to the table Records. If you want to label the column place the keyword as between the column name and uts label.
If you placed a white space in the column name (never saw, never did, don't even know if it's possible at all), try including the column name between single quotes. Or (much better) rename the column.
Related
The Error i get is
An unhandled exception of type 'System.Data.OleDb.OleDbException' occurred in System.Data.dll
Additional information: No value given for one or more required parameters.
but this is when all parameters a present code bellow:
private OleDbDataReader dbReader;// Data Reader object
string sConnection = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=ICTSchool.accdb";
string sql;
OleDbConnection dbConn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0; Data Source=ICTSchool.accdb");
OleDbCommand dbCommand;
public class ComboboxItem
{
public string Text { get; set; }
public object Value { get; set; }
public override string ToString()
{
return Text;
}
}
private void bAdd_Click(object sender, EventArgs e)
{
{
dbConn = new OleDbConnection(sConnection);
dbConn.ConnectionString = sConnection;
dbConn.Open();
string code = (cBQualification.SelectedItem as ComboboxItem).Value.ToString();
string sqlinsert = "INSERT INTO Student VALUES (" + tBStudentNum.Text + "," + tBStudentName.Text+","+ tBCellNo.Text+","+ code + ")";
Console.WriteLine("Test 'sqlinsert' "+ sqlinsert);
dbCommand = new OleDbCommand(sqlinsert, dbConn);
dbCommand.ExecuteNonQuery();
}
}
Here is part of the article about how to insert values in MS Access.
To add one record to a table, you must use the field list to define which fields to put the data in, and then you must supply the data itself in a value list. To define the value list, use the VALUES clause.
For example, the following statement will insert the values "1", "Kelly", and "Jill" into the CustomerID, Last Name, and First Name fields, respectively.
INSERT INTO tblCustomers (CustomerID, [Last Name], [First Name])
VALUES (1, 'Kelly', 'Jill')
You can omit the field list, but only if you supply all the values that record can contain.
INSERT INTO tblCustomers VALUES (1, Kelly, 'Jill', '555-1040',
'someone#microsoft.com')
Source MSDN How to: Insert, Update, and Delete Records From a Table Using Access SQL
The problem I see may be because of malformed SQL Statement. The string values( NVARCHAR, VARCHAR) should be enclosed within single quotes which I believe is not how you're doing now with following statement
string sqlinsert = "INSERT INTO Student VALUES (" + tBStudentNum.Text + "," + tBStudentName.Text+","+ tBCellNo.Text+","+ code + ")";
Try changing the SQL Statement to
string sqlinsert = $"INSERT INTO Student VALUES ({tBStudentNum.Text}, '{tBStudentName.Text}', {tBCellNo.Text}, '{code}')";
I've made an assumption in above case that tBStudentNum.Text and tBCellNo.Text are numeric values. If not, you can make appropriate changes to put the values inside single quote.
If you're using lower version of .net/C#, replace the $ expression with string.format function.
A number of observations:
You haven't specified the parameters in the SQL so we can only assume that there are four fields in the Student table.
You are not using named parameters - this is generally poor practice.
You are using concatenated values and SQL - this will leave you vulnerable to a SQL Injection attack
Any one of the text boxes might include a comma or other SQL formatting characters leading to SQL errors.
I am trying to insert these values:
int limit = 50000;
int acc_id = 1;
string query = "INSERT INTO CURRENT_ACCOUNT(C-ACCOUNT_NO,DAILY_LIMIT)
VALUES ('"+acc_id+"','"+limit+"')";
OracleCommand command = new OracleCommand(query, con);
command.ExecuteNonQuery();
But getting a missing comma exception:
C# {"ORA-00917: missing comma"}
Are you sure your CURRENT_ACCOUNT table contains a column with the name C-ACCOUNT_NO? Is the column named C_ACCOUNT_NO (with the dash - replaced with an underscore _) instead?
If the column name genuinely does contain a dash, wrap the column name in double-quotes:
string query = "INSERT INTO CURRENT_ACCOUNT(\"C-ACCOUNT_NO\",DAILY_LIMIT) " + // ...
You have to add semicolon at the end of query..
string query = "INSERT INTO CURRENT_ACCOUNT(C-ACCOUNT_NO,DAILY_LIMIT)
VALUES ("+acc_id+","+limit+");";
I'm trying to execute a very simple SQL statement on an Access database through C#.
The statement is something like this:
select M_PASSWORD from TB_USERS where M_USERNAME = 'myuser'
and this is the C# code I'm using to execute the SQL statement:
string connString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + sources.global_variables.db_source;
using (OleDbConnection connection = new OleDbConnection(connString))
{
connection.Open();
OleDbDataReader reader = null;
OleDbCommand command = new OleDbCommand("SELECT #1 from #2 WHERE #3='#4'", connection);
command.Parameters.AddWithValue("#1", db_column);
command.Parameters.AddWithValue("#2", db_table);
command.Parameters.AddWithValue("#3", db_where_column);
command.Parameters.AddWithValue("#4", db_where_value);
reader = command.ExecuteReader();
//rest of code
Once I get to the line reader = command.ExecuteReader();, the reader fails the execution of the query giving me the following error message: OleDBException was unhandled: Syntax error in query (Incomplete query clause).
I've debugged the code to see if I could see any wrong assignment in the parameters values, but they look fine.
Moreover, executing the exact same query on the Query Analyzer of the Database, I retrieve the value I want.
Could anyone give a tip to spot the problem and understand where I'm wrong?
I think you cant pick column names as parameter such that. It might be the problem.
Use if statement or other conditional statements for parameter and move your query to inside of your conditional statement.
I don't believe that parameters can be used in the fashion you posted. Parameters are used for filling in values (ie, placing a DateTime value into an update statement as the value of a DateTime column to be updated in a table).
Try changing your code such that the column names and table names are provided in text or are filled in as a string. You can build the query string up if you want to fill in different column names, different table names, and different column names in your where clause. So instead of what you posted, try something more like this:
string connString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + sources.global_variables.db_source;
using (OleDbConnection connection = new OleDbConnection(connString))
{
connection.Open();
OleDbDataReader reader = null;
string strQuery = "SELECT " + constStringColumnName1 + " FROM " + theTableNamePassedInAsString + " WHERE " + strWhereClauseBuiltEarlierInThisFunction + " = '#1'";
OleDbCommand command = new OleDbCommand( strQuery , connection);
command.Parameters.AddWithValue("#1", db_where_value);
reader = command.ExecuteReader();
//rest of code
}
Of course, you could format the string and plug in your changing selection column name, your table name, and your where clause. Build your select/command string, then use Parameters to fill in the actual value is the normal usage.
Try remove the ' on where parameter and use ? insted of # like that
OleDbCommand command = new OleDbCommand("SELECT ? from ? WHERE ?=?", connection);
command.Parameters.AddWithValue("column", db_column);
command.Parameters.AddWithValue("table", db_table);
command.Parameters.AddWithValue("where_column", db_where_column);
command.Parameters.AddWithValue("where_value", db_where_value);
I dont know if you can use parameters on column name. If it won´t running try to execute the query without parameters using concat and only use parameters on where value
I'm attempting to programmatically create a SQL table. I can create a table with a query, this is no issue at all. But I'd like the table name to have some relevance to the data inserted into it, as it's being used for quotations and invoices. Data entered from a DataGridView will be inserted into it (probably via bulkcopy, or something similar).
using (SqlCeCommand command = new SqlCeCommand(
"CREATE TABLE table1' (Weight INT, Name NVARCHAR, Breed NVARCHAR)", con))
works perfectly. However I'd like this code to work:
using (SqlCeConnection con = new SqlCeConnection(#"Data Source=|DataDirectory|\LWADataBase.sdf"))
{
con.Open();
try
{
string tableName = "" + quotenameTxt.Text + "-" +firstTxt.Text+ "-" + surenameTxt.Text;
using (SqlCeCommand command = new SqlCeCommand(
"CREATE TABLE '"+tableName.ToString()+"' (Weight INT, Name NVARCHAR, Breed NVARCHAR)", con))
{
command.ExecuteNonQuery();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Any suggestions? I get an error (as expected) but are unsure what I need to do.
I'm using SqlCe (and before anyone says "BulkCopy isn't supported", I know, I've got a reference that allows it)
The error I get is :
There was an error parsing the query. [ Token line number = 1,Token line offset = 16,Token in error = 1-2-3 ]
// "1-2-3" being the textbox values.
Change the dashes to underscores or surround the entire table name with [square brackets]
As was mentioned in comments above, make the following changes:
using (SqlCeCommand command = new SqlCeCommand(
"CREATE TABLE '"+tableName+"' (Weight INT, Name NVARCHAR, Breed NVARCHAR)", con))
tableName is already a string. No need to use .ToString() on it.
Also, you have a leading white space in your declaration of tableName:
string tableName = "" + quotenameTxt.Text + "-" + firstTxt.Text + "-"
+ surenameTxt.Text;
This makes the string " 1-2-3", not the "1-2-3" you are expecting.
Lastly, surround your tableName with [] to get it to work correctly:
using (SqlCeCommand command = new SqlCeCommand(
"CREATE TABLE '[" + tableName + "]' (Weight INT, Name NVARCHAR, Breed NVARCHAR)", con))
I have a windows form application in which I have a combobox and a text box.
I want to take the value from the text box and store it in a string(eg: txt). And take the value from the combobox and store it in another string(Eg: combo)
I want to run the below query
"select * from order where"+combo+"='"+txt+"'";
I get the the below error;
you have an error in your sql syntax check the manual that corresponds
to your mysql server version for the right syntax to use
near'='Brian'' at line 1
The problem is that you have no space between where and the value from the combo. This should do the trick:
"select * from order where "+combo+"='"+txt+"'";
Apart from that, don't do this, it opens you up for SQL Injection. You should use a SQLParameter to pass the value.
You are missing a white space after WHERE but since I didn't saw any complete answer, I take my chance..
I have a windows form application in which i have a combo box and a
text box.
Let's call your controls Combobox1 and TextBox1
I want to take the value from the text box and store it in a string(eg
txt). and take the value from the combo box and store it in another
string(Eg combo)
Ok. Let's take their values like;
string combo = Combobox1.Text;
string txt = TextBox1.Text;
So far, so good. Let's call your column names Column1 and Column2 in your table. So your query should be like;
"select * from order where Column1='" + combo + "' AND Column2='" + txt + "'";
But please don't use this way.
You should always use parameterized queries in your commands. It prevents, forget to use some quotes, commas etc.. But more important this kind of string concatenations are open for SQL Injection attacks.
And order is a reserved keyword in MySQL. You should use it with quotes.
Also use using statement to dispose your MySqlConnection and MySqlCommand.
Here a complete example;
using (var conn = new MySqlConnection(ConnectionString))
using (var cmd = conn.CreateCommand())
{
conn.Open();
cmd.CommandText = "select * from `order` where Column1=#combo AND Column2=#txt";
cmd.Parameters.AddWithValue("#combo", combo); // set the combo parameter
cmd.Parameters.AddWithValue("#txt", txt); // set the txt parameter
using (var reader = cmd.ExecuteReader())
{
if (reader.Read())
{
//You can read values here..
}
}
}
Try this :
"select * from order where " + combo + " = '" + txt + "';";
Just added a space between where and combo. Does it work ?
You forgot to take a space between where and combo
"select * from order where "+combo+"='"+txt+"'";
that will do
Apart from the missing space between WHERE and the column name, it may be you need to include the column name in backticks as well:
"select * from order where `" + combo + "` = '" + txt + "';";
Apart from SQL Injection and spacing issue in your syntax, whenever you need to construct the query where you are also injecting field names in it, we need to take care of following.
your combo should not accept a reserved SQL keyword. brackets can solve it but partially.
what if the combo field is not varchar, instead its int, then you need considerations to remove single quotes in your query.
have a look at sp_executesql, you may like it.