Below is a piece of code I have been working on for the past couple of days:
SqlConnection connectMOBILE = new SqlConnection("Server=OMADB03;Database=MOBILE;Trusted_Connection=True;");
string masterErrorString;
connectMOBILE.Open();
string stringIncorrectPassword = string.Concat(
"SELECT SERVICE_ID, RESPONSE_DATA, DATE_ENTERED",
"FROM WS_TRANSACTION",
"WHERE SERVICE_ID = 'GETUSERTOKENLOGIN'");
SqlCommand commandIncorrectPassword = connectMOBILE.CreateCommand();
commandIncorrectPassword.CommandText = stringIncorrectPassword;
SqlDataReader reader = commandIncorrectPassword.ExecuteReader();
while (reader.Read())
{
masterErrorString = reader.ToString();
BOAssistant.WriteLine(masterErrorString);
}
This code is using a class called BOAssistant that works like Console.WriteLine but instead writes to a log file.
What this code should be doing is collecting the results from my query and placing them in my log file, but when I run this program I get the following error message:
System.Data.SqlClient.SqlException (0x80131904): Incorrect syntax near 'SERVICE_ID'.
There are about 20+ more lines but this is the one that stands out the most. This is my first time writing a program that connects Visual Studio and SQL Server so I am wondering if it is something wrong in the code or I am missing something in my code to establish a stronger connection? What is in the code now is a result of research I have done on the internet. Also when I run the query in SQL Server it works so I know the syntax for query is correct.
When you combine your string you get incorrect SQL, because spaces are missing. string.Concat creates you this query:
SELECT SERVICE_ID, RESPONSE_DATA, DATE_ENTEREDFROM WS_TRANSACTIONWHERE SERVICE_ID = 'GETUSERTOKENLOGIN'
which obviously has some missing spaces.
Instead, update your query with spaces:
string stringIncorrectPassword = string.Concat(
"SELECT SERVICE_ID, RESPONSE_DATA, DATE_ENTERED ", // added space
"FROM WS_TRANSACTION ", // added space
"WHERE SERVICE_ID = 'GETUSERTOKENLOGIN'");
Related
I would like to find in my database which line has its "path" field's value equal to the string "c:\something\somethingelse\anotherthing.thing".
I found the line by browsing and copied it's content, before making an SQL request:
On C# side, my code looks like this:
EDIT: Due to #CompuChip 's comment, I edited my line for something that I hope may be better
String MyPath = "c:\\something\\somethingelse\\anotherthing.thing"
MyPath = String.Format("select * from x where path = '{0}'", MyPath);
Then I called the method to create and send the request to my database but I got an exception
I tried the request itself on my database but even if I copied the exact value it couldn't find the line:
Here's what I tried:
Select * from x where path = "c:\something\somethingelse\anotherthing.thing"
Select * from x where STRCMP(path, "c:\something\somethingelse\anotherthing.thing") = 0
Is there a good way to compare the strings correctly and find my line ?
Thank you for your time and have a nice day.
Edit 2: I also tried getting all my lines in C# then comparing them one by one.
It worked, but with 10K+ lines it's beginning to consume resources
Please, please, please don't construct your SQL queries like that.
The proper solution is using parameters, as explained here:
Why do we always prefer using parameters in SQL statements?
Your C# code would become something like this (adapted from the linked answer):
string sql = "select * from x where path = #path";
using (SqlCommand command = new SqlCommand(sql, connection))
{
var pathParam = new SqlParameter("path", SqlDbType.VarChar);
pathParam.Value = #"c:\something\somethingelse\anotherthing.thing";
command.Parameters.Add(pathParam);
var results = command.ExecuteReader();
}
or, for MySql,
string sql = "select * from x where path = ?path";
using (MySqlCommand command = new MySqlCommand(sql, connection))
{
var pathParam = new MySqlParameter("path",
#"c:\something\somethingelse\anotherthing.thing");
command.Parameters.Add(pathParam);
var results = command.ExecuteReader();
}
Assuming that you (have checked that you) actually have a matching record in the database, the problem is likely either with the quoting, or the escaping of the value.
If that is indeed the case, using parameters to retrieve the record is not only the safe thing to do, it will also make your quoting or escaping problem a non-issue.
It appears I have to do the same thing I do in C# and put two backslashes instead of one in the path, even in MySQL
Furthermore I also had to construct correctly my requests as #CompuChip hinted.
Thank you all for your help !
I'm trying to update a Database table and getting the error
"MySql.Data.MySqlClient.MySqlException: '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 'group='superadmin' WHERE
identifier='steam:steam:1100001098b5888'' at line 1'"
// Creates query to run
public void UpdateInfo(String jobTitle, int jobGrade, String adminLevel, String identifier) {
// Opens the database connection if it's not already open
if (!(databaseConnected)) {
openConnection();
}
// Creates query to run
String query = "UPDATE " + table + " SET job=#jobTitle, job_grade=#jobGrade, group=#adminLevel WHERE identifier=#identifier";
// Makes a new command
MySqlCommand cmd = new MySqlCommand(query, connection);
// Replaces the # placeholders with actual variables
cmd.Parameters.AddWithValue("#jobTitle", jobTitle);
cmd.Parameters.AddWithValue("#jobGrade", jobGrade);
cmd.Parameters.AddWithValue("#adminLevel", adminLevel);
cmd.Parameters.AddWithValue("#identifier", identifier);
// Executes it and if it's...
if (cmd.ExecuteNonQuery() > 0) {
// Successful
MessageBox.Show("Successfully updated information");
closeConnection();
return;
} else {
// Not successful
MessageBox.Show("Error with updating information!");
// Closes the connection again to prevent leaks
closeConnection();
return;
}
}
I tried your query on https://sqltest.net/ and noticed it highlighted "group" when I tried to create the table. I'm wondering if the problem might be the usage of "group" as a column name since it's a reserved word.
Is it possible to try renaming the column to group_level or adding back ticks around 'group' or "group" and seeing if that works?
So for example
'group'=#grouplevel
I found this thread and this thread on renaming the column where they had issues with "group" as a column name. Adding backticks seemed to solve both problems.
EDIT: As per OP, double quotes (") solved the issue instead of single. Edited answer to include.
Try change query like this
String query = "UPDATE " + table + " SET job='#jobTitle', job_grade=#jobGrade, group='#adminLevel' WHERE identifier='#identifier'";
if you input String value with query, you need to use 'this' for work
I hope this will work for you.
if not, you can use String.Format for that like this.
String Query = String.Format("Update `{0}` Set job='{1}', job_grade={2}, group='{3}' Where identifier='{4}'", table, jobTitle, jobGrade, adminLevel, identifier);
I am having an issue generating a SQL query using C#. To troubleshoot, I made the button that executes the query also display the query text in a textbox on the form. What's perplexing is that I get an error saying "Incorrect syntax near 'IF'" when the program tries to execute the query, but if I copy/paste the query from the textbox to SSMS it works fine.
The variable that stores the query looks like:
string myQuery = #"
SELECT DISTINCT filter.id_column INTO #temp1
FROM MasterDB.dbo.filter filter
LEFT JOIN ClientDB.dbo.codes codetable
ON filter.id_column=codetable.id_column
WHERE codetable.name IS NULL
DECLARE #code_id1 INT;
SET #code_id1 = (SELECT MAX(code_num) FROM ClientDB.dbo.codes)+1
EXEC('ALTER TABLE #temp1 ADD tempID INT IDENTITY(' + #code_id1 + ',1)')
GO
IF (SELECT COUNT(*) FROM #temp1)>0
BEGIN
DECLARE #code_id2 INT;
SET #code_id2 = (SELECT MAX(tempID) FROM #temp1)+1
UPDATE ClientDB.dbo.track
SET next=#code_id2 WHERE [trackname]='account'
END";
The C# code to populate the textbox with the query text and then run the query looks like:
using (SqlConnection myConnection = new SqlConnection(HostConnStr))
using (SqlCommand myCommand = myConnection.CreateCommand())
{
myCommand.CommandText = myQuery;
this.textBox1.Text = myCommand.CommandText;
myConnection.Open();
try { myCommand.ExecuteNonQuery(); }
catch (SqlException s) { MessageBox.Show(s.ToString()); }
myConnection.Close();
}
Does anyone know why the query text can be copied to SSMS and run fine, but throws a SQL exception when executed from C#? And how do I make the query run?
Critique on the query design will be appreciated, but I am more concerned with simply getting the query to execute since it does what I need it to do as-is.
EDIT: This may be a duplicate (I was thrown off by the error being near 'IF' when it appears that 'GO' is the problem, so my searches were in the wrong direction. However, I am still not sure that the answers provided in similar questions will work since I am under the impression that splitting the query into multiple commands will fail due to the later part of the query referencing a temporary table in the earlier part (will the temporary table not become unavailable after the first command is finished?).
It's the GO statement. You can replace it with ; in most instances.
In TSQL it's OK to have multiple statements separated by GO. In the ADO.NET version you can't do this.
The way to do this would be spilt the string on the GO and execute each independently. Such as this example,
string scriptText = #"...."
//split the script on "GO" commands
string[] splitter = new string[] { "\r\nGO\r\n" };
string[] commandTexts = scriptText.Split(splitter, StringSplitOptions.RemoveEmptyEntries);
foreach (string commandText in commandTexts)
{
//execute commandText
}
C# ... this works
string sql = "SELECT * FROM STATEMENTS WHERE [idTrip] = '2015Q15'";
command.CommandText = sql;
But when I try to replace the '2015Q15' with a variable as follows, it does not work
string sql = "SELECT * FROM STATEMENTS WHERE [idTrip] = '" + myVariable + "'";
command.CommandText = sql;
When I run through line by line, I can see that the str sql looks fine but it does not select any records
Try this:
command.CommandText = "SELECT * FROM STATEMENTS WHERE [idTrip] = #idTrip";
command.Parameters.AddWithValue("#idTrip", myVariable);
Aside from the danger for SQL injection...
Do you have checked for leading or trailing white spaces in myVariable? Use .Trim() on myVariable to rule this out. I assume you have checked the content of myVariable to be correct otherwise?
If still no results are returned: Trace the SQL that is actually arriving at the server with the SQL Server profiler. Capture the command, execute it in SQL Server Management Studio to make sure it executes & yields the expected results.
Is your database configured to be case-sensitive? Could this be the reason? If the letter casing in your myVariable content is not exactly the same as in your table it could have this effect also.
Similar question: Pass number as a column name in select statement of Sql
I have a column in a csv file that has a name of 0.000. How do I select it with a oledb select statement? Currently I have:
StringBuilder sbSelectItems = new StringBuilder();
sbSelectItems.Append("location_c, ");
sbSelectItems.Append("impb_, ");
sbSelectItems.Append("order_id, ");
sbSelectItems.Append(" `0.000` as shipCost, ");
sbSelectItems.Append("transmitta, ");
sbSelectItems.Append("piecelb ");
string sSelectStatement = "SELECT " + sbSelectItems.ToString() + " FROM [" + sFileName + "]";
but I get an error that '' is not a valid column. I've tried the [0.000], '0.000', "0.000" and what I have currently and I get the literal values or an error thrown for an invalid column. The file is auto generated through a program I don't have access to so I can't change the column name.
UPDATE
Trying the example from the first answer I got an error that said No value given for one or more required parameters. So I was confused and did a SELECT * FROM... and the column name, when I did that the column name, was tr110308#csv.01. I tried to select the value then doing tr110308csv#csv.01 but I was not able to.
Also using 0#000 didn't work...
#62 is the column I want.
Try changing your column name in your "select" statement to "0#000". Here is a sample which attempts to reproduce and then fix your issue.
Given a CSV file with the following content:
Foo,Bar,100.0,200
Alpha,Happy,8,5
Beta,Sad,19,2
A Select statement of the form
"Select Foo, `100.0` From "
Receives an OleDbException with the message...
'' is not a valid name. Make sure that it does not include invalid characters or punctuation and that it is not too long.
..which matches the error you received (or, I assume it does, you abbreviated and altered the message).
Changing the select to "100#0" was able to sidestep the issue.
Full repro code:
string fileName = "C:\\Temp\\test.csv";
string connectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"TEXT;HDR=YES;FMT=Delimited\";", Path.GetDirectoryName(fileName));
using (var connection = new System.Data.OleDb.OleDbConnection(connectionString))
{
string sql = "Select Foo, `100#0` From " + Path.GetFileName(fileName);
using (var adapter = new System.Data.OleDb.OleDbDataAdapter(sql, connection))
{
var table = new DataTable();
var result = adapter.Fill(table);
table.Dump(); // LinqPad method to display result for verification
}
}
You'll note the column name in the output matches the select statement (although you may still alias it, as your original SQL attempts to do). Indeed, the method of discovery here was to simply perform a "Select * From ..." and inspect the output. I found no source material beforehand, so interesting question!
Edit: With your update, the same approach is applicable. The name "tr110308csv#csv.01" is not legal for the select statement, but the name "tr110308csv#csv#01" is. Renaming the column (to match yours) in the test file and then using the altered version in the code produces the desired output, and I recommend you attempt it in your code, as well.