Connecting to database [closed] - c#

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 getting a run time error in my program when connecting to a SQL Server CE database.
Can anyone help me, and please don't write the whole code just a line of what needs to be changed to.
Here is my code:
string conString = Properties.Settings.Default.POSdatabaseConnectionString;
using (SqlCeConnection con = new SqlCeConnection(conString))
{
con.Open();
using (SqlCeCommand com = new SqlCeCommand("SELECT * FROM Customer where Customer ID ='" + this.useridtexbox.Text + "' and Name='" + this.nametexbox.Text + "'", con))
{
SqlCeDataReader reader = com.ExecuteReader();
int count = 0;
while (reader.Read())
{
count = count + 1;
}
if (count == 1)
{
MessageBox.Show("You have logged in succesfully");
Homepage homepage = new Homepage();
homepage.Show();
homepage.LabelText = ("Welcome " + reader["name"].ToString());
}
else
{
MessageBox.Show("Username and password is Not correct ...Please try again");
con.Close();
}
Error:
There was an error parsing the query. [ Token line number = 1,Token line offset = 39,Token in error = ID ]

I think the problem with the space in Customer ID,Try this
SqlCeCommand com = new SqlCeCommand("SELECT * FROM Customer where CustomerID ='" + this.useridtexbox.Text + "' and Name='" + this.nametexbox.Text + "'", con))

In your command, do not use string concatenation. That will fail badly and leave you open to SQL injection attacks.
Image what happens if I enter the following text into this.nametexbox.Text:
Joe'; DROP DATABASE; --
You don't want have someone like little Bobby Tables as user.
Use sql parameters.
If you have tables or fields with spaces, you to have a word with your DBA. If you cannot change it, make sure you use the correct syntax:
WHERE [Customer ID] = '12345'

Make sure you CustomerID column have space
Always use parameterized query to avoid SQL Injection
How does SQLParameter prevent SQL Injection
SqlCeCommand com = new SqlCeCommand = "SELECT * FROM Customer where CustomerID=#CustomerID and
name=#name";
con.Parameters.AddWithValue("#CustomerID", valuesTextBox.Text);
con.Parameters.AddWithValue("#name", namwTextBox.Text);

Related

Insert comma into MS Access database using Visual Studio [duplicate]

This question already has answers here:
Single quote handling in a SQL string
(3 answers)
Closed 6 months ago.
I'm creating an application using Visual Studio 2019, with a connection to an MS Accsess database to add, get, modify and delete values inside the database.
I'm willing to insert a text that could contain a comma, for example : Gousse d'ail. But I know there will be a problem because the string has to be surrounded by commas. So I added a backslash before every extra comma inside the text I'm willing to insert.
The thing is a get an error message saying there is a syntax error, I believe it's because of the backslash.
Here is the message I get :
System.Data.OleDb.OleDbException (0x80040E14) : Syntax error (missing operator) in query expression " 'Gousse d\'ail', unite = 'kg', allergene = False, fournisseurID = 1 WHERE ingrédientID = 40; "
Everything works really well until there is comma.
Here is the method I use to insert into the database:
public void UpdateIngédient(int ingredientID, InfoIngredient ing)
{
string query = "UPDATE Ingrédients ";
query += "SET nom = '" + ing.Nom + "', unite = '" + ing.Unité + "', allergene = " + ing.Allergene + ", fournisseurID = " + ing.Fournisseur;
query += " WHERE ingredientID = " + ingredientID + ";";
OleDbCommand com = new OleDbCommand(query, oleConnection);
com.ExecuteNonQuery();
}
Your query is begging for SQL injection, as well as bugs exactly like the one you've encountered.
If you're doing any work with a SQL table (or OLE in your case) I strongly recommend spending some time to look into SQL injection to understand the risks.
It's very easy to defend against SQL injection and a rewrite of your code is shown below to protect against it.
void UpdateIngédient(int ingredientID, InfoIngredient ing)
{
string query = "UPDATE Ingrédients SET nom = #nom, unite = #unite, allergene = #allergene, fournisseurID = #fournisseur WHERE ingredientID = #ingredientID;";
OleDbCommand cmd = new OleDbCommand(query, oleConnection);
cmd.Parameters.Add(new OleDbParameter("#nom", ing.Nom));
cmd.Parameters.Add(new OleDbParameter("#unite", ing.Unité));
cmd.Parameters.Add(new OleDbParameter("#allergene", ing.Allergene));
cmd.Parameters.Add(new OleDbParameter("#fournisseur", ing.Fournisseur));
cmd.Parameters.Add(new OleDbParameter("#ingredientID", ingredientID));
OleDbCommand com = new OleDbCommand(query, oleConnection);
com.ExecuteNonQuery();
}
This should safeguard against "unexpected" characters in your strings such as the ' character

Exception thrown while trying to run sql through c# [closed]

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
I am trying to run a database query through c#. I am trying to pass a parameter into my sql statement but I am getting an exception saying invalid near #Agent_ID.
My code is like this
SqlCommand command = new SqlCommand("Select Csr_DISBURSEMENTDATE, Csr_AGENTNUMBER, Csr_TOTCURREARNINGS, Csr_MISCADJUSTMENTS, Csr_YTDTOTALCOMM, Csr_PAYMENTMETHOD From Cm_Opt_Csr_CommStatement_S " +
"inner join Cm_Opt_Con_Contract_S on Con_WritingCode = Csr_AgentNumber" +
"inner join Cm_Opt_Agt_Agent_S on agt_ID = Con_AgentID" +
"where Agt_ID = #AgentID");
command.Parameters.AddWithValue("#AgentID", Con_agentID);
command.Connection = conn;
SqlDataReader rdr = null;
rdr = command.ExecuteReader();
Con_agentID is a guid and in the database table the column which it maps to is a uniqueidentifer. I am stuck at this point. Could someone please point out the mistake in the syntax.
The exception thrown is
System.Data.SqlClient.SqlException: 'Incorrect syntax near 'Agt_ID'.'
You are missing spaces between words when you continue on to next line.
SqlCommand command = new SqlCommand("Select Csr_DISBURSEMENTDATE, Csr_AGENTNUMBER, Csr_TOTCURREARNINGS, Csr_MISCADJUSTMENTS, Csr_YTDTOTALCOMM, Csr_PAYMENTMETHOD From Cm_Opt_Csr_CommStatement_S " +
"inner join Cm_Opt_Con_Contract_S on Con_WritingCode = Csr_AgentNumber " +
"inner join Cm_Opt_Agt_Agent_S on agt_ID = Con_AgentID " +
"where Agt_ID = #AgentID");
command.Parameters.AddWithValue("#AgentID", Con_agentID);
command.Connection = conn;
SqlDataReader rdr = null;
rdr = command.ExecuteReader();

Incorrect syntax near '= '. in code c# [closed]

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;

I can't execute the SqlCommand [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
hello guys I have got this code
cmd = new SqlCommand();
cmd.Connection = baglanti;
cmd.CommandText = "(musteriadi,musterisoyadi,gsm,email,sirketadi,Adres,Notlar) VALUES('" + txtMusteriAdi.Text.Trim() + "','" + txtMusteriSoyadi.Text.Trim() + "','" + txtGsm.Text.Trim() + "','" +txtEmail.Text.Trim() + "','" +txtSirketAdi.Text.Trim() + "','" +txtAdres.Text.Trim() + "','" +txtNotlar.Text.Trim() +"');";
baglanti.Open();
cmd.ExecuteNonQuery();
baglanti.Close();
I defined the cmd as a public SqlCommmand and in every time when the code come to the cmd.ExecuteNonQuery() it falls to catch what can I do .
Because you forget INSERT INTO part for your statement. Like;
INSERT INTO tableName(musteriadi,musterisoyadi,gsm,email,sirketadi,Adres,Notlar)
But much more important, you should always use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.
Also use using statement to dispose your connection and command automatically instead of calling Close method manually.
using(var baglanti = new SqlConnnection(yourConnectionString))
using(var cmd = baglanti.CreateCommand())
{
cmd.CommandText = #"INSERT INTO tableName(musteriadi,musterisoyadi,gsm,email,sirketadi,Adres,Notlar)
VALUES(#ad, #soyad, #gsm, #email, #sirket, #adres, #notlar)";
// Add your parameters values with Add method considering their types and size.
baglanti.Open();
cmd.ExecuteNonQuery();
}

IF ELSE condition asp net with SQL Server [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
string conn = "";
conn = ConfigurationManager.ConnectionStrings["Conn"].ToString();
SqlConnection objsqlconn = new SqlConnection(conn);
objsqlconn.Open();
SqlCommand objcmd = new SqlCommand("IF (select 1 from PRODUCT where PRODUCT_NAME=" + Master_product_txt.Text + ")=1
PRINT 'ALREADY AVAILABLE'
ELSE
Insert into PRODUCT(PRODUCT_NAME) Values('" + Master_product_txt.Text + "')
GO", objsqlconn);
objcmd.ExecuteNonQuery();
MessageBox.Show("Details Successfully Added!!!");
I'm trying check the data base values before insert the value, I've wrote query for it, it's working in sql server environment, I could not able to implement same thing in Visual Studio
go is a SSMS (SQL Server Management Studio) statement, it won't work from C#
use parameters to avoid SQL injection
it is unusual to use the Hungarian obj prefix in C#
A quick try at a better version:
var cmd = new SqlCommand(#"
IF NOT EXISTS (SELECT * FROM PRODUCT WHERE PRODUCT_NAME = #NAME)
BEGIN
INSERT INTO PRODUCT (PRODUCT_NAME) VALUES (#NAME)
END
", sqlconn);
cmd.Parameters.AddWithValue("#NAME", Master_product_txt.Text);
cmd.ExecuteNonQuery();
SqlCommand objcmd = new SqlCommand("SELECT 1 from PRODUCT WHERE PRODUCT_NAME=#NAME" , objsqlconn);
//NVarChar
cmd.Parameters.Add("#NAME", SqlDbType.NVarChar,20).Value = Master_product_txt.Text;
objsqlconn.Open();
readr = SelectCommand.ExecuteReader();
if (!readr.HasRows)
{
`// code to insert values here.
}`
PRINT 'ALREADY AVAILABLE' will not work here.For capturing print statement message you have to add an event handler to the InfoMessage event on the connection.And use parametrized query where ever possible. ;)

Categories

Resources