Database System.Data.SqlClient.SqlException - c#

I'm trying to use database:
SqlConnection sqlcon = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=D:\DB\LogiDB.mdf;Integrated Security=True;Connect Timeout=30");
string query = "Select * from tbl_Login Where username = '" + textBox1.Text.Trim().ToLower() + "' and password = '" + textBox1.Text.Trim().ToLower() + "'";
SqlDataAdapter sda = new SqlDataAdapter(query, sqlcon);
DataTable dtbl = new DataTable();
sda.Fill(dtbl);
if (dtbl.Rows.Count == 1)
{
//
}
my files is:
dbo.Table.sql
LogiDB.mdf
LogiDB_log.ldf
tbl_Login.sql
not sure what I'm doing wrong but when I press to button I got this with line sda.Fill(dtbl);:
An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
Additional information: Invalid object name 'tbl_Login'.

As the error says: Invalid object name 'tbl_Login'
This might mean:
tbl_Login table doesn't exist in you database
you are connecting to wrong database
Since you have tbl_Login.sql script, I guess it contains table definition. Therefore you would need to run script to create table in your LogiDB database.
Here there is example how to connect to local database

Here is my code work perfectly,
You can try this and compare your code
SqlConnection cn = new SqlConnection("Data Source=AVREST\\SQLEXPRESS;Initial Catalog=master;Integrated Security=True");
cn.Open();
SqlCommand cmd = new SqlCommand("select loginID,loginPassword from logintavle where loginID='" + textBox1.Text + "'and loginPassword='" + textBox2.Text + "'", cn);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
//sda.SelectCommand = cmd;
DataTable dataset = new DataTable();
sda.Fill(dataset);
if (dataset.Rows.Count > 0)

Related

Microsoft visual studio says "Incorrect syntax used near the word Table"

I am trying to create an sql database for a school project, but I keep on getting the error that an invalid syntax word was used near the word "Table".
string title = "Failed";
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\Stitc\OneDrive\Documents\Data.mdf;Integrated Security=True;Connect Timeout=30");
string query = "Select Count (*) From Table Where Username = '" + textBox1.Text.Trim() + "' and Password = '" + textBox2.Text.Trim() + "'";
SqlDataAdapter sda = new SqlDataAdapter(query, con);
DataTable dt = new DataTable();
try
{
sda.Fill(dt);
if (dt.Rows.Count == 1)
{
this.Hide();
Form1 main = new Form1();
}
else
{
MessageBox.Show("The wrong password or username was entered! Please try again", title);
}
}

Error :An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll

I am programming an application with C# and SQL Server and I want to to connect to my database and display the result of a search query and I tried many methods, dataset and reader, but the same error always shows up - please help me!
The error:
An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
Additional information: Syntaxe incorrecte vers '1012'.
Here is the code part (med_ID is the name of textbox, dgrAffich_tab is a dataGridView):
private void button1_Click(object sender, EventArgs e)
{
int ID;
ID = int.Parse(med_ID.Text);
SqlConnection conn = new SqlConnection(#"Data Source=DESKTOP-HCLRURF\SQLEXPRESS;Initial Catalog=ydb;Integrated Security=True");
SqlCommand cmd = new SqlCommand("SELECT Quantite FROM TabRestitue WHERE Tab_medID= %" + ID + "% ORDER BY DateDePeremption ASC ");
conn.Open();
cmd.Connection = conn;
DataSet dt = new DataSet();
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(dt);
dgrAffich_tab.DataSource = dt;
conn.Close();
}
Your Sql command has an syntax error, the 1012 the error is referencing is your med_Id value.
A string, in SQL, must be encapsulated between single quote (')
The Sql Server currently receive this string (there's no quote around %1012%)
SELECT Quantite FROM TabRestitue WHERE Tab_medID= %1012% ORDER BY DateDePeremption ASC
The valid Sql would be
SELECT Quantite FROM TabRestitue WHERE Tab_medID='%1012%' ORDER BY DateDePeremption ASC
But the way your are doing it is unsafe because of Sql Injection. The recommended way would be to use SqlParameter. Also, SqlConnection, SqlCommand and SqlDataAdapter are disposable, so i've added a using to dispose them.
int ID;
ID = int.Parse(med_ID.Text);
using (SqlConnection conn = new SqlConnection(#"Data Source=DESKTOP-HCLRURF\SQLEXPRESS;Initial Catalog=ydb;Integrated Security=True"))
{
using (SqlCommand cmd = new SqlCommand("SELECT Quantite FROM TabRestitue WHERE Tab_medID= #medId ORDER BY DateDePeremption ASC "))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#medId", "%" + ID + "%");
conn.Open();
cmd.Connection = conn;
DataSet dt = new DataSet();
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
sda.Fill(dt);
}
dgrAffich_tab.DataSource = dt;
conn.Close();
}
}
To avoid errors, build the LIKE expression as a string in T-SQL and use a strongly-typed parameterized query.
SqlCommand cmd = new SqlCommand("SELECT Quantite FROM TabRestitue WHERE Tab_medID= '%' + CAST(#ID AS varchar(10)) + '%' ORDER BY DateDePeremption ASC;");
cmd.Parameters.Add("#ID", SqlDbType.Int).Value = ID;

MYSQL Connector not connecting

I have this code atm in c# and the MYSQL connection wont work:
int chk;
MySqlConnection con = new MySqlConnection(#"Data Source=sql9.freemysqlhosting.net;port=3306;Initial Catalog=new;UserId=sql9FFFFF9;password=X3FFFFYX8;");
con.Open();
MySqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from sql9164489.users where username='" + txt_user.Text + "' and password='" + txt_pass.Text + "'";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
da.Fill(dt);
chk = Convert.ToInt32(dt.Rows.Count.ToString());
//If Correct
if (chk == 1)
{
MessageBox.Show("Connected");
}
else
{
MessageBox.Show("Incorrect");
}
con.Close();
con.Opern() raises an error:
Authentication to host 'sql9.freemysqlhosting.net' for user 'sql9FFFFF9' using method 'mysql_native_password' failed with message: Access denied for user 'sql9FFFFF9'#'188.244.39.23' (using password: YES)
I guess it's pretty clear
Download MySQL connector for .net and your working will be more easy as database will display in server explorer and then you can copy and paste the connection string from there.
Here is link

Store a timer value in a database? c#

I have a global variable which is set up for the timer, "I", the program I'm creating has a user play a game level and store their level time in a database with other users. This is what I have already.
public static class Global
{
public static int I = 0;
}
^ this is the global variable for the timer.
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Adam\Documents\Data2.mdf;Integrated Security=True;Connect Timeout=30");
SqlDataAdapter sad = new SqlDataAdapter("Select Count(*) From Login where Username= '" + txtUsername.Text + "' and Password='" + txtPassword.Text + "'", con);
SqlCommand cmd = new SqlCommand("INSERT INTO HighScore (Username, Score) VALUES(#Username,#Score)", con);
DataTable dt = new DataTable(); //empty table
sad.Fill(dt);
if (dt.Rows[0][0].ToString() == "1")
{
con.Open();
cmd.Parameters.AddWithValue("#USERNAME", txtUsername.Text);
cmd.Parameters.AddWithValue("#Score", Global.I);
}
else // else it will display this error
{
MessageBox.Show("Please enter the correct login details");
}
^^ this is the code for the end screen of the game, as you can see i've tried taking the Global.I and addwithvalue #Score which is in the HighScore table in my database.
Now when i click the button it doesn't write anything to the database but I don't get any errors when i try and save, this is why i'm confused.
Any help would be appreciated, Thanks.
before executing any command you first must open the connection. You are opening the connection after calling Fill()!!. You will also have to execute cmd. Try:
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Adam\Documents\Data2.mdf;Integrated Security=True;Connect Timeout=30");
SqlDataAdapter sad = new SqlDataAdapter("Select Count(*) From Login where Username= '" + txtUsername.Text + "' and Password='" + txtPassword.Text + "'", con);
SqlCommand cmd = new SqlCommand("INSERT INTO HighScore (Username, Score) VALUES(#Username,#Score)", con);
con.Open();
cmd.Parameters.AddWithValue("#USERNAME", txtUsername.Text);
cmd.Parameters.AddWithValue("#Score", Global.I);
DataTable dt = new DataTable(); //empty table
sad.Fill(dt);
cmd.ExecuteNonQuery();
It is also admirable that you know how to correctly use parameters, however you use them only in 1 case instead of both queries.

Why I get Incorrect syntax near '=' error

I tried bind a label from datatable
I get this error
Incorrect syntax near '='.
at this line
da.Fill(dt);
My code : Page_Load
LbLID.Text =this.Page.Request.QueryString["DI"].ToString();
SqlConnection con = new SqlConnection("Data Source=local;Initial Catalog=DB;User
ID=sa;Password="pass);
SqlDataAdapter da = new SqlDataAdapter("select * from Table1 where ID= " +
LbLID.Text.Trim(), con);
System.Data.DataTable dt = new System.Data.DataTable();
da.Fill(dt);
lblS1.Text = dt.Rows[0][4].ToString();
lblS1.DataBind();
You can't break normal string literals across multiple lines, also your closing quote is misplaced:
SqlConnection con = new SqlConnection("Data Source=local;Initial Catalog=DB;User ID=sa;Password=pass");
Or use a verbatim literal, which you can break across multiple lines:
SqlConnection con = new SqlConnection(
#"Data Source=local;
Initial Catalog=DB;
User ID=sa;
Password=pass");
That said, your code is vulnerable to SQL injection attacks. For your own sake, and the sake of your users, you really should use parameterized queries instead of concatenating your SQL queries like that.
Here's a quick example:
using(var con = new SqlConnection(...))
{
var cmd = new SqlCommand("select * from Table1 where ID = #ID", con);
con.Open();
cmd.Parameters.AddWithValue("#ID", LbLID.Text.Trim());
var da = new SqlDataAdapter(cmd);
var dt = new DataTable();
da.Fill(dt);
lblS1.Text = dt.Rows[0][4].ToString();
lblS1.DataBind();
}
Some other tips: You should avoid using select * queries, since your database schema might change, and that would break any existing code. It would be better to select only the column you're interested in and make a simple call to ExecuteScalar.
Try this:
SqlDataAdapter da = new SqlDataAdapter("select * from Table1 where ID ='" +
LbLID.Text.Trim() + "'", con);
However note that it a very bad code which is vulnerable to sql injection.
So you should try this:
var com = new SqlCommand("SELECT * FROM Table1 WHERE ID=#id", con);
com.Parameters.AddWithValue("id",LBLID.Text.Trim());
var da = new SqlDataAdapter(com);
Or shorter:
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM Table1 WHERE ID=#id", con);
da.SelectCommand.AddWithValue("id",LBLID.Text.Trim());
Its a SQL error. You aren't passing in a valid ID.
It's one of two things.
Option A: Your ID is a string. In which case.. you need to use single quotes:
SqlDataAdapter da = new SqlDataAdapter("select * from Table1 where ID= '" + LbLID.Text.Trim() + "'", con);
Option B: Your LbLId is wrong.. you're checking for ["DI"] .. when I think it should be ["ID"]:
LbLID.Text =this.Page.Request.QueryString["ID"].ToString();
I do not see any problem in the code at da.Fill(). But I see another issue at the following statement:
SqlConnection con = new SqlConnection("Data Source=local;Initial Catalog=DB;User
ID=sa;Password="pass);
...Password="pass); - rather is should be
...Password=" + pass);
OR
...Password=pass");
I am wondering you are not getting an undefined variable error for pass*.

Categories

Resources