Incorrect Syntax Near 'Student' - c#

I am attempting to create a function that will allow a variable assignment, but i keep getting an error:
private static void DatabaseSelect(string ToBeSelected, string WhichTable, string Equality1, string Equality12)
{
SqlConnection con = new SqlConnection(#"Connection");
var dataSet = new DataSet();
var cmd = new SqlCommand("SELECT Firstname FROM Student WHERE User_ID = '" + "001" + "'", con);
//var cmd = new SqlCommand("SELECT '"+ToBeSelected+"' FROM '"+WhichTable+ "' WHERE '"+Equality1+"' = '"+Equality12+"'", con);
var dataAdapter = new SqlDataAdapter { SelectCommand = cmd };
dataAdapter.Fill(dataSet);
Console.WriteLine( dataSet.Tables[0].Rows[0][ToBeSelected].ToString());
}
When I use the line
var cmd = new SqlCommand("SELECT Firstname FROM Student WHERE User_ID = '" + "001" + "'", con);
It should theoretically, when the variables equal the same string as the line above, be the same as the line
var cmd = new SqlCommand("SELECT '"+ToBeSelected+"' FROM '"+WhichTable+ "' WHERE '"+Equality1+"' = '"+Equality12+"'", con);
But when I try to run the lower line it gives the error message (At the line Filling dataAdapter):
"An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
Additional information: Incorrect syntax near 'Student'."
If I am unclear please say so.Any help would be appreciated, thank you.

I do see some issues with your MySQL syntax
SELECT '"+ToBeSelected+"' FROM '"+WhichTable+ "' WHERE '"+Equality1+"' = '"+Equality12+"'"
Should translate to a MySQL Statement of:
SELECT 'ColumnName' FROM 'TableName' WHERE 'ColumnName2' = 'SomeValue'"
The first issue I'm seeing is all the single quotes.. Column names, tables names should be surrounded by "ticks" (the button to the left of the 1) not Single quotes.
I would start there, I'm reading further into you code now.

Related

C# asp.net MySQL either Null or Input string was not in a correct format

So, when I try to call a string with asp.net such as e7af78997ef220a557c97a1a4c11e0c2 the return always comes back null. I know for a fact it isn't null (all ID's are in that format or in an IP format). and it works when I input an int column.
So my problem is that The return is always null, and Visual Studio says
"An unhandled exception of type 'System.FormatException' occurred in
PresentationFramework.dll
Additional information: Input string was not in a correct format."
I know it has to do with MySqlCommand SelectCommand = new MySqlCommand("select * from a3bans.bans where GUID = '" + ban.GuidOrIP + "' ; ", conDataBase); and I'm almost positive it has to do with
'" + ban.GuidOrIP + "' ; ", conDataBase);`
I think I've tried a million ways and and either have gotten syntax errors or Null
I think the issue has to do with the Database input rather than output. Input as in "select" I put in the ID just using a regular query and it populated the information, however. When trying to use my tban (the { getter; Setter;} it just returns Null...
Every thing that I have researched has referenced to a button with .Text and nothing seems to help with a getter and setter..
I am sure it's something very simple I am over looking. I'm very new to C# and what may take you 2 minutes may take me 6 hours... like this...
[HttpPost]
[Route("A3Bans/searchBan")]
public string oSearchBan(tBan ban)
{
{
tBan bans = new tBan();
string dbConnection = "datasource=127.0.0.1;port=3306;username=admin;password=00000";
MySqlConnection conDataBase = new MySqlConnection(dbConnection);
MySqlDataReader dbReader;
MySqlCommand SelectCommand = new MySqlCommand("select * from a3bans.bans where GUID = '" + ban.GuidOrIP + "' ; ", conDataBase); // Returning a null value?!
conDataBase.Open();
dbReader = SelectCommand.ExecuteReader();
while (dbReader.Read())
{
tBan searchBan = new tBan();
searchBan.GuidOrIP = dbReader.GetString("GUID");
searchBan.BanType = dbReader.GetString("BanType");
searchBan.BanReason = dbReader.GetString("Reason");
searchBan.Proof = dbReader.GetString("Proof");
bans = searchBan;
}
dbReader.Close();
return bans.Proof;
}
}
If I replace the query string with string selectQuery = "Select * FROM a3bans.bans WHERE BanID=" + int.Parse(schBanID.Text); It will return the proper values from the client side. and If i were to translate it to the API it alreturns the correct values. But it is an int and not a string.
Update:
Tried, Still not working.
Man I still can't wrap my head around it.
[HttpPost]
[Route("A3Bans/searchBan")]
public string oSearchBan(tBan ban)
{
{
tBan bans = new tBan();
string dbConnection = "datasource=127.0.0.1;port=3306;username=admin;password=00000";
MySqlConnection conDataBase = new MySqlConnection(dbConnection);
MySqlDataReader dbReader;
conDataBase.Open();
// Returns a null value from bans.Proof
// If placing a /w real GUID without null fields, rather than "ban.GuidOrIP" , the return populates properly.
MySqlCommand selectCommand = new MySqlCommand("SELECT * FROM a3bans.bans WHERE (GUID) LIKE(#GUID)", conDataBase);
selectCommand.Parameters.AddWithValue("#GUID", bans.GuidOrIP);
selectCommand.ExecuteNonQuery();
dbReader = selectCommand.ExecuteReader();
This still returns null

'System.Data.SqlClient.SqlException' occurred in System.Data.dll but was not handled in user code. Additional information: Incorrect syntax near 'b'

I keep getting this error and I have checked my code several times to find a solution but to no avail.
private void PopulateotherNames()
{
string query = "SELECT a nickName FROM otherNames a" +
"INNER JOIN nameNicki b ON a.Id = b.otherNamesId" +
"WHERE b.realNameId=#realNameId";
using (connection = new SqlConnection(connectionString))
using (SqlCommand command = new SqlCommand(query, connection))
using (SqlDataAdapter adapter = new SqlDataAdapter(command))
{
command.Parameters.AddWithValue("#realNameId", listRealName.SelectedValue);
DataTable NickNameTable = new DataTable();
adapter.Fill(NickNameTable);
listNickName.DisplayMember = "nickName";
listNickName.ValueMember = "Id";
listNickName.DataSource = NickNameTable;
}
}
Try this out... Missing your alias and no spaces in some places. Look into stored procedures and you wouldn't have any of these kinds of problems.
string query = "SELECT a.nickName FROM otherNames a " +
"INNER JOIN nameNicki b ON " +
"a.Id = b.otherNamesId" +
" WHERE b.realNameId=#realNameId";

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.

SqlCommand - conversion from varchar to int

Hello I have got this code :
SqlCommand sc2 = new SqlCommand("SELECT ... WHERE akce=" + zakce.Text, spojeni);
spojeni.Open();
object vysledek2 = sc2.ExecuteScalar(); // This is the exception line
I'm receving following Exception:
System.Data.SqlClient.SqlException (0x80131904)Conversion failed when
converting the varchar value '137000-01' to data type int.
On the exception line when I set the breakpoint on vysledek2 is null and then the exception occurs.
Never. Ever. Concatenate. Input.
SqlCommand sc2 = new SqlCommand("SELECT SUM(ISNULL(payments,0)) AS sumpaymentsFROM clientpayments WHERE akce=#acke", spojeni);
sc2.Parameters.AddWithValue("acke", zakce.Text);
Also - commands, connections, etc are all IDisposable - you should use using around each of them.
const string sqlSelect = #"SELECT ... WHERE akce=#akce";
using (spojeni = new SqlConnection(connectionString))
using(var command = new SqlCommand(sqlSelect,spojeni))
{
command.Parameters.AddWithValue("#akce", zakce.Text);
command.Connection.Open();
object vysledek2 = command.ExecuteScalar();
}
Firstly, try changing
SqlCommand sc2 = new SqlCommand("SELECT SUM(ISNULL(payments,0)) AS sumpaymentsFROM clientpayments WHERE akce=" + zakce.Text, spojeni);
to something like
SqlCommand sc2 = new SqlCommand("SELECT SUM(ISNULL(payments,0)) AS sumpaymentsFROM clientpayments WHERE akce='" + zakce.Text + "'", spojeni);
Secondly, have a look at what SQL Injection is and how to use parametereized queries.

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