Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
Hi i have problem with execute Query with Parameter in access database:
OleDbConnection cnn;
OleDbCommand cmdselect2;
string sqlselect2 = null;
string baza = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + #"L:\Windykacja\Sdro\Projekt\projekt.accdb";
connetionString = baza;
sqlselect2 = "SELECT count(POS_Pesel_regon) as Suma FROM POS WHERE POS_Pesel_regon = #PR";
cnn = new OleDbConnection(connetionString);
cnn.Open();
cmdselect2 = new OleDbCommand(sqlselect2, cnn);
Int32 PR1 = Convert.ToInt32(cmdselect2.ExecuteScalar());
cmdselect2.Parameters.AddWithValue("#PR", textBox6.Text);
cmdselect2.Dispose();
cnn.Close();
It's say that my paramter is missing
In insert it works perfectly :)
will be thankfull for any sugestions.
cheers
Because you try to execute your command before you add your parameter. Change those lines
Int32 PR1 = Convert.ToInt32(cmdselect2.ExecuteScalar());
cmdselect2.Parameters.AddWithValue("#PR", textBox6.Text);
to
cmdselect2.Parameters.AddWithValue("#PR", textBox6.Text);
Int32 PR1 = Convert.ToInt32(cmdselect2.ExecuteScalar());
A few things more;
Use using statement to dispose your connection and command automatically instead of calling Close or Dispose methods manually.
Don't use AddWithValue as much as you can. It may generate unexpected and surprising results sometimes. Use Add method overload to specify your parameter type and it's size.
using(var cnn = new OleDbConnection(connetionString))
using(var cmdselect2 = cnn.CreateCommand())
{
cmdselect2.CommandText = #"SELECT count(POS_Pesel_regon) as Suma FROM POS
WHERE POS_Pesel_regon = #PR";
cmdselect2.Parameters.Add("#PR", OleDbType.VarChar).Value = textBox6.Text;
// I assumed your column type as VarChar
cnn.Open();
int PR1 = (int)cmdselect2.ExecuteScalar();
}
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
so, I have this code
MySqlConnection connection = new MySqlConnection("Server=localhost;Port=3306; Database=brez-db;Uid=root;Pwd=root;");
try {
connection.Open();
String Query = "SELECT 1 FROM users_table WHERE user_Username='" + usernameTB.Text + "' AND user_Password='" + passwordTB.Password + "'";
MySqlCommand myCommand = new MySqlCommand(Query, connection);
MySqlDataReader myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
String str = myReader.GetString("user_Username").ToString();
MessageBox.Show(str);
}
}
catch(Exception ex) { throw; }
finally { }
but
while(myReader.Read()){}
returns only 1 and 0 . 1 if there is a value inside and 0 if there's nothing.
I've tried many things to get the value but nothing, any suggestion?
I'm writing a wpf C# app
PS: I know that its a good thing to use parameters for security, but I want to make a simple code for now
Remove 1 after the select. Also you should use query for the name of your string,not Query,it looks like it is reserved for something.
Also,you should get your string like this:
string sUsername= myReader["ColumnName"].ToString();
or like this
string sUsername= myReader[0].ToString();
And in the finally you are missing connection.Close();
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I'm developing a c# windows form application program that saves the info about the student like name course year and etc. My code in saving to sql database works but when it comes to retreiving the info i get these error incorrect syntax near '='. i think the error is in the retreive code.please help :)
Here is the retrieve code:
try
{
string sql = "SELECT studnum,course,f_name,l_name,color_image FROM table3 WHERE f_name=" + textBoxfname.Text + "";
if (conn.State != ConnectionState.Open)
conn.Open();
command = new SqlCommand(sql, conn);
SqlDataReader reader = command.ExecuteReader();
reader.Read();
if (reader.HasRows)
{
labeloutputstudnum.Text = reader[0].ToString();
labeloutputcourse.Text = reader[1].ToString();
labeloutputfname.Text = reader[2].ToString();
labeloutputlname.Text = reader[3].ToString();
byte[] img = (byte[])(reader[4]);
if (img == null)
pictureBox3.Image = null;
else
{
MemoryStream ms = new MemoryStream(img);
pictureBox3.Image = Image.FromStream(ms);
}
}
else
{
textBoxstudno.Text = "";
textBoxcourse.Text = "";
textBoxfname.Text = "";
textBoxlname.Text = "";
pictureBox3.Image = null;
MessageBox.Show("does not exist");
}
conn.Close();
}
catch (Exception ex)
{
conn.Close();
MessageBox.Show(ex.Message);
}
string sql = "SELECT studnum,course,f_name,l_name,color_image FROM table3 WHERE f_name=#Name";
command = new SqlCommand(sql, conn);
command.Parameters.Add(new SqlParameter("#Name", textBoxfname.Text));
I see multiple errors:
The most obvious, always use parameters in your sql statements.
Always use using blocks to clean up connections.
Do not reuse connections, this is bad practice as sql server will automatically (by default unless you turn it off exclititly) use connection pooling.
// DO NOT reuse connections, create a new one when needed!
using(var conn = new SqlConnection(/use a connection from the web/app .config/))
{
const string sql = "SELECT studnum,course,f_name,l_name,color_image FROM table3 WHERE f_name = #name";
command = new SqlCommand(sql, conn);
command.Parameters.Add(new SqlParameter("#name", SqlDbType.VarChar) { Value = textBoxfname.Text});
conn.Open();
/* rest of code unchanged but do not call conn.Close(), the using block will do this for you
}
So to answer your question, your sql query has incorrect syntax. I would break point on the sql string to see exactly what's wrong. It should be obvious when you do that.
The REAL problem though is that you're exposing your application to SQL injection. Let's look at a basic example of what you have.
"SELECT * FROM table WHERE id ='" + userinput.Text + "'";
So the user inputs some value and it gets dumped in there for the query. Simple right?
What happens if the user inputs this
' OR 1=1; --
Well let's see what your sql string turns into when that's added
SELECT * FROM table WHERE id = '' OR 1=1; -- '
So now, your query string says select the id OR where 1=1 which means where true, which means everything.
SQL injection is a real threat and the only way to stop it is to implement counter measures right from the start.
Please look into parameterization. It's very easy in C#.
MSDN Article on C# Parameterization
You have to use single quotes for string parameters/fields in SQL:
string sql = "SELECT studnum,course,f_name,l_name,color_image FROM table3 WHERE f_name='" + textBoxfname.Text + "'";
But it is better (more secure) to use parameters:
string sql = "SELECT studnum,course,f_name,l_name,color_image FROM table3 WHERE f_name=#name";
if (conn.State != ConnectionState.Open)
conn.Open();
var command = new SqlCommand(sql, conn);
command.Parameters.Add("#name", SqlDbType.NVarChar).Value = textBoxfname.Text;
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I'm getting a weird syntax error when trying to view an image from the database. It is statement an incorrect syntax error near an operator. I have no idea what is happening as im pretty sure this is all fine until it runs.
"incorrect syntax near '= "
View image code
using (SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0; AttachDbFilename=C:\Users\Donald\Documents\Visual Studio 2013\Projects\DesktopApplication\DesktopApplication\Student_CB.mdf ;Integrated Security=True"))
{
con.Open();
try
{
string sql = "Select Image, Image_Name FROM Recipe_Image Where Image_ID =" + imageidTxt.Text + "";
if (con.State != ConnectionState.Open)
con.Open();
command = new SqlCommand(sql, con);
SqlDataReader reader = command.ExecuteReader();
reader.Read();
if(reader.HasRows)
{
nameTxt.Text = reader[0].ToString();
byte[] img = (byte[])(reader[1]);
if (img == null)
picImg.Image = null;
else
{
MemoryStream ms = new MemoryStream(img);
picImg.Image = Image.FromStream(ms);
}
}
con.Close();
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
con.Close();
}
Your SQL syntax is invalid, mostly because you're not actually in control of it. (You have what's called a SQL Injection Vulnerability.) Instead of executing user-input values as code, treat them as values. First, define a static query with a parameter placeholder:
string sql = "Select Image, Image_Name FROM Recipe_Image Where Image_ID = #Image_ID";
Then when you build your SqlCommand object, add a parameter for that placeholder:
// the query implies that the ID is a number, so make it a number...
int imageId = 0;
if (!int.TryParse(imageidTxt.Text, out imageId)
{
// entered text wasn't a number, return an error?
}
// then add that number as a parameter
command.Parameters.Add("#Image_ID", SqlDbType.Int).Value = imageId;
This way you've defined a static query at design-time, rather than building a dynamic (and currently unknown) one at runtime. So the syntax of the SQL query is known and can be validated as part of the design.
Note: This answer has been changed pretty heavily to correct some misinformation.
Previously, this answer suggested using Convert.ToInt32(x). This will not directly pass an integer to the database; however, it will happily yell at you (throw an exception) if the value passed in is not an integer.
What does happen is that the query string is passed down to sql (as a string) and the sql parser interprets the value as an int based on (little sql goblins).
Instead, you should probably be doing something more like this:
public void ReadFromDatabase()
{
int idToFind;
//check that imageidTxt.Text is an integer
if (Int32.TryParse(imageidTxt.Text, out idToFind))
{
//we have an integer, so look at the database
string sql = "SELECT * FROM Table WHERE ID=" + idToFind;
//connect to/read from DB
}
else
{
//fail spectacularly
}
}
This will add (trivial) error checking before you hit the database, and pass in the query as valid syntax.
Note that this answer does not address issues like SQL Injection that have been brought up in comments/answers, and even if it doesn't make much sense to you at the moment, it's very much worth learning about.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
i'm a student in a vocational high school and i'm still new to programming, i have an assignment to create a application using c#, and i have a problem in joining 3 tables to display on datagridview..
i have tried the query on mySql it works just fine, but when i applied it in my c# line of code it didnt work it shows "no database selected", can somebody help me on this, here's my full code
string constring = "datasource=localhost;port=3306;username=root;password=root";
MySqlConnection conDataBase = new MySqlConnection(constring);
MySqlCommand cmdDataBase = new MySqlCommand("select book_detail.id_bookdetail, location.location_id, location.location_name, book.book_id, book.title from location inner join book_detail on location.location_id = book_detail.location_id inner join book on book_detail.book_id = book.book_id; ", conDataBase);
try
{
MySqlDataAdapter sda = new MySqlDataAdapter();
sda.SelectCommand = cmdDataBase;
DataTable dbdataset = new DataTable();
sda.Fill(dbdataset);
BindingSource bSource = new BindingSource();
bSource.DataSource = dbdataset;
transfer_view.DataSource = bSource;
sda.Update(dbdataset);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
Your connection string should specify a database name:
Server=myServerAddress;Database=myDataBase;Uid=myUsername;Pwd=myPassword;
^^^^^^^^^^^^^^^^^^^
(Port 3306 is the default MySql port)
Ref. MySQL connection strings
Do a "use mydbname"
Perhaps it is the last optional parameter in prior string that u are not providing
Can do "select database()" to show current db in use
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I'm trying to get a label to display how many entries exist in a database. And I'm using the most ridiculously simple FROM I can imagine. And I'm getting spammed with "Syntax error in FROM clause" rather than having my label update. Syntax is an error I get a lot when I use a system reserved name for a table or column. But the table name I'm using works in other statements, so I assume that's not the issue, and it's the ONLY variable. Unless it's something other than the FROM and it's lying to me, which is entirely possible...
if (DateTime.Now.Millisecond > 500)
{
try
{
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=access.mdb";
conn.Open();
OleDbCommand cmmd = new OleDbCommand("SELECT * FROM probe)", conn);
using (OleDbDataReader myReader = cmmd.ExecuteReader())
{
DataTable dt = new DataTable();
dt.Load(myReader);
int count = dt.Rows.Count;
lblCount.Text = count.ToString();
conn.Close();
}
}
catch (OleDbException expe)
{
MessageBox.Show(expe.Message);
}
}
}
SELECT * FROM probe)
should be
SELECT * FROM probe
?
Change
OleDbCommand cmmd = new OleDbCommand("SELECT * FROM probe)", conn);
to
OleDbCommand cmmd = new OleDbCommand("SELECT * FROM probe", conn);