Syntax Error on INNER JOIN in MySQL - c#

I get a error when trying to inner join databases from a MySqL server.
I get this 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 'lines INNER JOIN snippets ON snippets.id = lines.snippetid_fk WHERE lines.snippe' at line 1
Im Coding in ASP.Net C#.
This is my function that gives the error:
MySqlConnection conn = new MySqlConnection();
string mysql = "Server=***;Database=***;User=***;pwd=***";
conn.ConnectionString = mysql;
MySqlCommand cmd = new MySqlCommand();
cmd.CommandText = "SELECT * FROM lines " +
"INNER JOIN snippets ON snippets.id = lines.snippetid_fk " +
"WHERE lines.snippetid_fk = 1";
cmd.Connection = conn;
DataTable dt = new DataTable();
MySqlDataAdapter adapter = new MySqlDataAdapter(cmd);
adapter.Fill(dt);
Repeater_codebank.DataSource = dt;
Repeater_codebank.DataBind();

According to documentation, lines is in the list of MySQL reserved words.
For your query, to work, you must add backticks around the table name:
cmd.CommandText = "SELECT * FROM `lines` " +
"INNER JOIN snippets ON snippets.id = lines.snippetid_fk " +
"WHERE `lines`.snippetid_fk = 1";

Related

C# WPF mysql string

I'm creating a wpf app that is connected to localhost database, it has 2 tables, now I ran into an error but I'm not sure what is wrong in the code. Can anyone help?
I'm getting this error:
An unhandled exception of type 'MySql.Data.MySqlClient.MySqlException'
occurred in MySql.Data.dll
Additional information: You have an error in your SQL syntax; check
the manual that corresponds to your MariaDB server version for the
right syntax to use near 'left join author on
book.author_id=author.id' at line 1
private void Filter_TextChanged(object sender, TextChangedEventArgs e)
{
connection.Open();
MySqlCommand cmd = connection.CreateCommand();
cmd.CommandText = "SELECT * FROM book where book.name like ('" + Filter.Text + "%') left join author on book.author_id=author.id";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
da.Fill(dt);
_dataView = new System.Data.DataView(dt);
_dataView.Sort = "name ASC,id ASC";
BooksGrid.DataContext = dt;
connection.Close();
}
Change your query to
cmd.CommandText = "SELECT * FROM book left join author on book.author_id=author.id where book.name like ('" + Filter.Text + "%') and book.author_id=author.id";
The additional "book.author_id=author.id" clause at the end is to ensure that you only get records that match on author_id.
Also instead of cmd.ExecuteNonQuery(), you should try and use the cmd.ExecuteReader() since you are retrieving rows.

System.Data.SqlClient.SqlException: Incorrect syntax near ')'

I am getting an error in my SQL command with which I am trying to retrieve values from a SQL Server database. It is showing a error in browser as mentioned in title. If I remove the brackets it shows error in AND operator
string jdate = (string)Session["jdate"];
string clas = (string)Session["class"];
string scode = (string)Session["scode"];
string dcode = (string)Session["dcode"];
cn = new SqlConnection(ConfigurationManager.ConnectionStrings["dummyConnectionString"].ToString());
// error shows up on this line
string slct = "SELECT Route.Route_Source, Route.Route_Destination, Flight.Flight_Name, Schedule.Depart_Time, Schedule.Arr_Time, Schedule.Route_rate_Ad , Seats." + jdate +
"Schedule.Sch_id FROM Schedule INNER JOIN Flight ON Schedule.Flight_Id = Flight.Flight_id INNER JOIN Route ON Schedule.Route_id = Route.Route_id INNER JOIN Seats ON Seats.Sch_id = Schedule.Sch_id WHERE (Route.Route_Source =" + scode + ") AND (Route.Route_Destination =" + dcode + ") AND (Seats.Class=" + clas + ") ORDER BY Schedule.Depart_Time, Schedule.Arr_Time, Flight.Flight_Name";
cn.Open();
SqlDataAdapter da = new SqlDataAdapter(slct, cn);
DataSet ds = new DataSet();
da.Fill(ds);
SearchView.DataSource = ds;
SearchView.DataBind();
You should use a parameterized query.
This would allow a more understandable query text, avoid simple syntax errors
(like the missing comma at the end of the first line (jdate)),
avoid Sql Injections and parsing problems with strings containing quotes or decimal separators
string slct = #"SELECT Route.Route_Source, Route.Route_Destination,
Flight.Flight_Name, Schedule.Depart_Time, Schedule.Arr_Time,
Schedule.Route_rate_Ad, Seats." + jdate + ", Schedule.Sch_id " +
#"FROM Schedule INNER JOIN Flight ON Schedule.Flight_Id = Flight.Flight_id
INNER JOIN Route ON Schedule.Route_id = Route.Route_id
INNER JOIN Seats ON Seats.Sch_id = Schedule.Sch_id
WHERE (Route.Route_Source = #scode)
AND (Route.Route_Destination =#dcode)
AND (Seats.Class=#class)
ORDER BY Schedule.Depart_Time, Schedule.Arr_Time, Flight.Flight_Name";
cn.Open();
SqlCommand cmd = new SqlCommand(slct, cn);
cmd.Parameters.AddWithValue("#scode", scode);
cmd.Parameters.AddWithValue("#dcode", dcode);
cmd.Parameters.AddWithValue("#class", clas);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);

How to run a SQL query command for Access from another SQL query command?

The problem is that I need to Execute a SQL command for a query on Access which I already have running perfectly.
using (OleDbConnection _Connn = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Pos\POS_DB(" + _DS.sNumCaja + ").accdb"))
sSQL =
"SELECT Sum(tblVentasArticulos.Cantidad) AS SumOfCantidad, Sum(tblVentasArticulos.Precio) AS SumOfPrecio, qryDepartamentos.Departamento" + " " +
"FROM qryDepartamentos RIGHT JOIN (tblVentasArticulos RIGHT JOIN tblVentas ON tblVentasArticulos.Folio = tblVentas.Folio) ON qryDepartamentos.idDepartamento = tblVentasArticulos.Dep" + " " +
"GROUP BY qryDepartamentos.Departamento;";
OleDbCommand cmd = new OleDbCommand(sSQL, _Connn);
That piece of code works well, but inside the sSQL string, the "qryDepartamentos" is a query I made inside Access from a table on another Access DataBase. Is there a way of making the Query before and storing it inside a DataSet to use it as a variable for another SQL command? I tried something like this:
DataTable results = new DataTable();
OleDbDataAdapter adapter;
using (OleDbConnection conn = new OleDbConnection(connString))
{
OleDbCommand cmd = new OleDbCommand("SELECT tblDepartamentos.* FROM tblDepartamentos", conn);
conn.Open();
adapter = new OleDbDataAdapter(cmd);
adapter.Fill(results);
DataView dv = new DataView(results);
}
Now I don't know how to add or use the DataSet data inside the first sSQL command, in order to replace the "qryDepartamentos".
Thank you but I figured it'd be easier to use a function and giving the parameters so it would return a simple string. Thank You All! :)

Mysql inner join column with spaces

I have 2 tables which are the customers table and orders table.
Basically my problem is that it always give me an error which is 'unknown field list'.
I have tried in phpmyadmin XAMPP it works the only problem is that when I use it in VS studio c# it gives me an error.
I'm confused the back ticks '`' don't work but the back ticks work on localhost.
Please help me.
This is my sql syntax:
SQL = "SELECT o.`Order ID`, o.Description, o.Amount
FROM tbl_orders AS o
INNER JOIN tbl_customers AS c ON o.`Order ID` = c.`Order ID`
WHERE c.`Customer ID` = '" + cust_id + "'";
cmd.Connection = dbCon;
cmd.CommandText = SQL;
rdr= cmd.ExecuteReader();
dt.Load(rdr);
Have tried deleting and retyping the ` around the column names incase it didnt copy correctly. Also try putting a # before the string so.
SQL = #"<the sql>";
this works on mysql xampp
MySqlConnection sqlConnection = new MySqlConnection(#"Server=localhost;Database=test;");
var sql = #"SELECT o.`Order ID`, o.Description, o.Amount
FROM tbl_orders AS o
INNER JOIN tbl_customers AS c ON o.`Order ID` = c.`Order ID`
WHERE c.`Customer ID` = 1";
sqlConnection.Open();
MySqlCommand sqlCommand = new MySqlCommand(sql,sqlConnection);
sqlCommand.ExecuteNonQuery();
sqlConnection.Close();
Columns with spaces in their name should be enclosed in square brackets.
Try
SQL = "SELECT o.[Order ID], o.Description, o.Amount
FROM tbl_orders AS o
INNER JOIN tbl_customers AS c ON o.[Order ID] = c.[Order ID]
WHERE c.[Customer ID] = '" + cust_id + "'";
cmd.Connection = dbCon;
cmd.CommandText = SQL;
rdr= cmd.ExecuteReader();
dt.Load(rdr);
http://tinyurl.com/qcf45vf
What is the use of the square brackets [] in sql statements?

SQL Query Problems with Tables

public void SPROC_LoadGroups()
{
//This gets the table name.
string tablename = cboNetChannel.SelectedItem.ToString();
SqlConnection sqlConnectionCmdString = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Rick\Documents\Visual Studio 2010\Projects\Server\database\ClientRegit.mdf;Integrated Security=True;User Instance=True");
//This is the table name and Query that identifies with the selected table
string Command = "SELECT Client_Groups" + "FROM" + tablename;
SqlCommand sqlCommand = new SqlCommand(Command, sqlConnectionCmdString);
SqlDataAdapter objDA = new SqlDataAdapter(sqlCommand);
DataSet dsGroups = new DataSet();
objDA.Fill(dsGroups, "dtGroup");
cboExistingG.DataSource = dsGroups.Tables["dtGroup"];
cboExistingG.DisplayMember = "Client_Groups";
//cboExistingG.ValueMember = "ID";
}
Error I am getting is this {"Incorrect syntax near '-'."}
I got a situation is it possible to query as table with a name similar to a GUID value
my table name is 43d5377-0dcd-40e6-b95c-8ee980b1e248
I am generating groups that are identified with a Networking Data table that is named 43d5377-0dcd-40e6-b95c-8ee980b1e248 The table name is allowed and SQL does not prohibit such table names.
This is my code I am getting an error, I am table mapping with this by creating a Query that allows me to identify the query with the selected table value.
If your table name is similar as a GUID add [] block
something like:
string Command = "SELECT Client_Groups FROM [" + tablename+ "]";
Best Regards
You were missing a space between the concatination of these two strings:
"SELECT Client_Groups" + "FROM"
change to
"SELECT Client_Groups " + "FROM "
SqlCommand cmd;
cmd = new SqlCommand("SELECT client_Groups FROM Table name where name='" + txtbox. Text + "' , lastname='" + txtbox. Text + "'", con);

Categories