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.
Related
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 have a table in SQLite with the following structure:
+-------+------+------+
| id |name |value |
|int |text |int |
+-------+------+------+
I am attempting to follow this guide on using sqlite databases in Unity. I am able to query the sqlite_master table to retrieve the only database table name using the following code:
_dbConnection = (IDbConnection)new SqliteConnection(_dbURI);
_dbConnection.Open();
string sqlStatement = "SELECT name FROM sqlite_master WHERE type='table' AND name='" + tableName + "';";
_dbCommand = _dbConnection.CreateCommand();
_dbCommand.CommandText = sqlStatement;
_dbReader = _dbCommand.ExecuteReader();
while (_dbReader.Read())
{
Debug.Log("Table: " + _dbReader.GetString(0));
}
However, when I attempt to query from the table itself to get the maximum ID using similar code my DataReader returns a null row:
_dbConnection = (IDbConnection)new SqliteConnection(_dbURI);
_dbConnection.Open();
string sqlStatement = "SELECT max(id) FROM " + tableName + ";";
_dbCommand = _dbConnection.CreateCommand();
_dbCommand.CommandText = sqlStatement;
_dbReader = _dbCommand.ExecuteReader();
while (_dbReader.Read())
{
Debug.Log("MaxId = " + _dbReader.GetInt32(0));
}
The null causes a conversion error with the call to _dbReader.GetInt32(0). When I write the sql statement to the log and paste it into my database browser it yields a number, so the query should be returning a value.
I'm not clear on why similar code works when querying sqlite_master but not my other table.
I've also tried ExecuteScalar with no success.
Thanks!
EDIT:
tableName is equal to "unit_def"
error message is
InvalidCastException: Cannot cast from source type to destination type.
Mono.Data.Sqlite.SqliteDataReader.VerifyType (Int32 i, DbType typ)
using count(*) yields a 0, so it seems that unity can't see the data in the table?
Also, oddly, changing the code messed up the GUI elements in my editor for some reason.
I solved the issue, hopefully this answer is helpful to others:
The issue was tricky to troubleshoot since
the correct database was being referenced
all code was correct
the sql query did return a result when run in my database browser
The problem is that I am using the DB Browser for Sqlite, which I am new to. I had written rows of data to the database so that my query would return results within the browser, but apparently these changes are not written to the database file for other applications to see until the "Write Changes" button is pushed.
Hopefully this helps anyone else who might be new to the db browser and stumbles into this error!
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'");
I would like to selected dynamic data from entity framework as per below.
if I select "Select * from TableName" in queryString it works fine but if I select only selected column/columns it does not work and throws an exception.
Working ok
string queryString = #"SELECT * FROM context.TableName ";
DbSqlQuery<SampleTable> result = context.SampleTable.SqlQuery(queryString);
Throws Exception
columnList is generated run time from SampleTable which may consists one or more columns.
string queryString = #"SELECT " + String.Join(",", columnList) + " FROM context.TableName ";
DbSqlQuery<SampleTable> result = context.SampleTable.SqlQuery(queryString);
Exception:
The data reader is incompatible with the specified 'context.TableName ... A member of the type, does not have a corresponding column in the data reader with the same name.
As per my understanding EF try to map all columns but above query does not have same number of columns as set in code and so it throws exception.
You can check the below steps :
Use the alias names of columns in your columnList (ex: tablename.Id instead of Id).
That all the column names in your columnList are mapped in the Entity.
Check that the column names in your columnList are same as of the Entity.
Hope this will help.
I tried to search a lot for tutorials on Npgsql and c#. but I couldn't resolve the below problem.
When I run the program, my programs stop and breaks at execute query. and when I try debug and check the return value from the execute reader is empty.
below is the sample code:
string user=textBox1.Text;
NpgsqlConnection dataconnect = new NpgsqlConnection(
"Server=127.0.0.1;Port=5432;User Id=dbuser;Password=dbpass;Database=dbname;");
string query = "Select USERNAME from helperdata.credentials where USERNAME = "
+ textBox1.Text + " and PASSWORD = " + textBox2.Text;
dataconnect.Open();
NpgsqlCommand command = new NpgsqlCommand(query, dataconnect);
NpgsqlDataReader reader = command.ExecuteReader();
if(reader.Read())
{
MessageBox.Show("Login Successful");
}
else
{
MessageBox.Show("Login failed");
}
reader.Close();
dataconnect.Close();
When I try to run the below query in Pgsql it returns the data.
Select "USERNAME" from helperdata.credentials where "USERNAME" = 'admin'
I am new to Npgsql.
I would also like if someone could provide me some good tutorial sites which provides detail explanation of Npgsql and C#.
Thanks in advance.
I have identified two problems in your code. The first the usage of uppercase letters on PostgreSQL identifiers. PostgreSQL allows identifiers with other than simple lowercase letter, but only if you quote them.
In fact, you can use, for instance:
CREATE TABLE helperdata.credentials (... USERNAME varchar, ...);
But PostgreSQL will convert it to:
CREATE TABLE helperdata.credentials (... username varchar, ...);
So, to make it really left with uppercase, you have to quote it as following:
CREATE TABLE helperdata.credentials (... "USERNAME" varchar, ...);
And that seems to be the way you have created your table, and the problem with that is that always you refers to that table in a query, you'll have to quote it. So the beginning of your query should be:
string query = "Select \"USERNAME\" from helperdata.credentials ... ";
My recommendation, is to modify your column and table names to don't use such identifiers. For this case you can do:
ALTER TABLE helperdata.credentials RENAME COLUMN "USERNAME" TO username;
The second problem, is the lack of string quotation when you concatenated the username from the textbox into the query. So, you should do something as the following (BAD PRACTICE):
string query = "Select \"USERNAME\" from helperdata.credentials where \"USERNAME\" = '"
+ textBox1.Text + "' and \"PASSWORD\" = '" + textBox2.Text + "'";
There is a huge problem with that, you can have SQL injection. You could create a function (or use one from Npgsql, not sure if there is) to escape the string, or, more appropriately, you should use a function that accept parameters in the query using NpgsqlCommand, which you can simple send the parameters or a use a prepared statement.
Check the Npgsql documentation, and find for "Using parameters in a query" and "Using prepared statements" to see examples (there are no anchors in the HTML to link here, so you'll have to search).