Syntax error while trying to fetch data from MySql - c#

So I am trying to fetch a value from the database, selecting the row using WHERE INT.
conn = new MySqlConnection(DBdetails.connStr);
conn.Open();
query = "SELECT * FROM tables WHERE table=#tafel";
MySqlCommand cmd = new MySqlCommand(query, conn);
cmd.Parameters.AddWithValue("#tafel", tafel);
cmd.ExecuteNonQuery();
However it wont pass 'cmd.ExecuteNonQuery()', it throws a error saying the syntax isnt right like: "near table=1", "near table=2"
I tried fetching a other one in the same table that is a var char and it worked perfectly.
Don't really see what I am doing wrong. The 'table' column is a int and 'tafel' is a int to.
Thanks!

Put your field name table in backticks (table is a reserved word in MySQL) :
query = "SELECT * FROM `tables` WHERE `table` = #tafel";

As others said, table is a reserved word in MySQL. You need to use quote with it like
query = "SELECT * FROM tables WHERE `table` = #tafel";
However, the best solution is to change the name to a nonreserved word.
Also use using statement to dispose your MySqlConnection and MySqlCommand like;
using(MySqlConnection conn = new MySqlConnection(DBdetails.connStr))
using(MySqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "SELECT * FROM tables WHERE `table` = #tafel";
cmd.Parameters.AddWithValue("#tafel", tafel);
conn.Open();
cmd.ExecuteNonQuery();
}
By the way, I don't understand why you use ExecuteNonQuery with SELECT statement. It just executes your query. It doesn't even return any value.
If you want to get the result of your query, you can use ExecuteReader method which returns SqlDataReader as your result rows.

Related

Insert foreign key into table with SQL query using C#

I have a database with 3 tables Identification, Identification_group and Group.
The Identification_group table has 2 foreign key columns, Identificaiton_id and Group_id.
In my form you can select the Group Number and it returns the right Group_id to the Identification_group table.
Is it possible to write a SQL query that uses the last Identification_id and the Group_id (from the selection field in my form) and writes this to the Identification_group table?
string sqlquery1 = "Insert into [dbo].[identification_group] (fk_group_id,fk_identification_id values (#fk_group_id,#fk_identification_id;";
SqlCommand schreiben = new SqlCommand(sqlquery1, myConnection);
myConnection.Open();
schreiben.Parameters.AddWithValue("#fk_identification_id", intidentification_id);
schreiben.Parameters.AddWithValue("#fk_group_id", Wil_Jls_idComboBox.SelectedValue);
schreiben.CommandText = sqlquery;
schreiben.ExecuteNonQuery();
myConnection.Close();
Sorry for the bad formatting, first time posting here.
Thank you in advance
Please try the below:
You have an issue with your SQL statement whereby you did not close the brackets. Also, you only need the # symbol in the SQL statement, and not in the C# code.
// Create the query
string query = "Insert into [identification_group] (fk_group_id, fk_identification_id) values (#fk_group_id, #fk_identification_id)";
// Create the SQL command
SqlCommand schreiben = new SqlCommand(query, myConnection);
// Open the SQL connection
myConnection.Open();
// Bind the parameters
schreiben.Parameters.AddWithValue("fk_identification_id", intidentification_id);
schreiben.Parameters.AddWithValue("fk_group_id", Wil_Jls_idComboBox.SelectedValue);
// Bind the command
schreiben.CommandText = query;
// Execute the command
schreiben.ExecuteNonQuery();
// Close the connection
myConnection.Close();

SqlCommand Select Command Aliases

I have this code:
SqlConnection Connection = new SqlConnection("data source=.;initial catalog=testdb;integrated security=sspi");
SqlCommand Command = new SqlCommand("select * from (select count(studentid) from student) as student", Connection);
Connection.Open();
Command.ExecuteNonQuery();
I expect the query comes from the user, so I need to filter it after the the select is written my way:
select * from (user query) as table
but it throws an error:
No column name was specified for column 1 of 'student'.
because some times columns must be aliased if it a function like count or avg
I need to use this way to filter the query after the user write it. Also I know where will not work after grouping and having must have an aggregation method at the SQL query...
Any ideas?
This should probably be a comment but I think the formatting here makes it clearer.
Logically there is no difference between
SELECT *
FROM ({query}) AS STUDENT
and
{query}
So what are you actually trying to do?
You just missing alias for count of students
select * from (select count(studentid) as CountOfStudents from student) as student
You have made some mistakes both in code and SQL syntax. The Error you receive is due to the fact that you have a confused query asking the count of the studednts without giving it the name, then you select this single value and try to give a name to a table... Besides, you use an ExecuteNonQuery that as its name tells executes some SQL on SQL server and does not retrieve anything, this kind of command is usually used to Execute statements to Insert or update data. The Correct code, is the following:
SqlConnection Connection = new SqlConnection("data source=.;initial
catalog=testdb;integrated security=sspi;persist security info=true");
SqlCommand Command = new SqlCommand("select count(studentid) AS StudentsNumber from student", Connection);
Connection.Open();
object result = Command.ExecuteScalar();
MessageBox.Show(result.ToString());

ORA-00911: invalid character

I create two table in my oracle (11g) database like this:
create table "test" ("id" int);
create table test ("id" int);
Then in my C# program there is a problem :
OracleConnection conn = new OracleConnection(-myConnectionString-);
conn.Open();
OracleCommand command = new OracleCommand("select * from test;", conn);
var v = command.ExecuteReader();
OracleCommand command = new OracleCommand("select * from \"test\";", conn);
var v = command.ExecuteReader();
for both command.ExecuteReader() I have an "ORA-00911: invalid character" error.
Remove ; (semi-colon) from the end of SQL string
In case other people wind up here looking for how to include multiple statements in a single command, you need to wrap your statements within begin and end. This will stop the invalid character errors due to the semi-colons. For example:
var command = new OracleCommand(#"
begin
select * from test;
select * from test2;
end;")
Why are you using semicolon in the query...It just be taken as invalid character.....
You have to remove the semicolon(;) from the query and do like this:
OracleConnection conn = new OracleConnection(-myConnectionString-);
conn.Open();
OracleCommand command = new OracleCommand("select * from test", conn);
var v = command.ExecuteReader();
OracleCommand command = new OracleCommand("select * from \"test\"", conn);
var v = command.ExecuteReader();
For more detail of this error, you can read here.
This isn't this guy's problem, but hopefully this will help someone out there:
I often have this problem with single quotes hidden inside inline comments, like so:
select foo
from bar
where
/* some helpful comment with a "can't" or somesuch */
baz='qux'
The unmatched single quote in the comment causes all kinds of drama, and oracle doesn't go out of its way to help you figure that out.
Replace the sqldatasource parameter ? with :Column_name in the delete, update and insert commands.

C# 'select count' sql command incorrectly returns zero rows from sql server

I'm trying to return the rowcount from a SQL Server table. Multiple sources on the 'net show the below as being a workable method, but it continues to return '0 rows'. When I use that query in management studio, it works fine and returns the rowcount correctly. I've tried it just with the simple table name as well as the fully qualified one that management studio tends to like.
using (SqlConnection cn = new SqlConnection())
{
cn.ConnectionString = sqlConnectionString;
cn.Open();
SqlCommand commandRowCount = new SqlCommand("SELECT COUNT(*) FROM [LBSExplorer].[dbo].[myTable]", cn);
countStart = System.Convert.ToInt32(commandRowCount.ExecuteScalar());
Console.WriteLine("Starting row count: " + countStart.ToString());
}
Any suggestions on what could be causing it?
Here's how I'd write it:
using (SqlConnection cn = new SqlConnection(sqlConnectionString))
{
cn.Open();
using (SqlCommand commandRowCount
= new SqlCommand("SELECT COUNT(*) FROM [LBSExplorer].[dbo].[myTable]", cn))
{
commandRowCount.CommandType = CommandType.Text;
var countStart = (Int32)commandRowCount.ExecuteScalar();
Console.WriteLine("Starting row count: " + countStart.ToString());
}
}
Set your CommandType to Text
command.CommandType = CommandType.Text
More Details from Damien_The_Unbeliever comment, regarding whether or not .NET defaults SqlCommandTypes to type Text.
If you pull apart the getter for CommandType on SqlCommand, you'll find that there's weird special casing going on, whereby if the value is currently 0, it lies and says that it's Text/1 instead (similarly, from a component/design perspective, the default value is listed as 1). But the actual internal value is left as 0.
You can use this better query:
SELECT OBJECT_NAME(OBJECT_ID) TableName, st.row_count
FROM sys.dm_db_partition_stats st
WHERE index_id < 2 AND OBJECT_NAME(OBJECT_ID)=N'YOUR_TABLE_NAME'

Schema from stored procedure

I have a procedure, I want to read schema of the procedure. To retrieve view schema I use the query shown here. Same way I want to get schema of stored procedure. How to get it? Plz show some syntax.
public static DataTable SchemaReader(string tableName)
{
string sql = string.Format("Select * from {0}", tableName);
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.CommandType = CommandType.Text;
SqlDataReader reader = cmd.ExecuteReader();
DataTable schema = reader.GetSchemaTable();
reader.Close();
conn.Close();
return schema;
}
If have any query plz ask.Thanks in advance.
you could do
public static DataTable SchemaReader(string tableName)
{
string sql = "MySP";//replace this with your store procedure name
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataReader reader = cmd.ExecuteReader();
DataTable schema = reader.GetSchemaTable();
reader.Close();
conn.Close();
return schema;
}
Hope this help
This is an answer that does not call the SP - if you do, you may inadvertently affect data:
SELECT * FROM sys.dm_exec_describe_first_result_set ('owner.sprocName', NULL, 0) ;
This returns the result set :
is_hidden
column_ordinal
name
is_nullable
system_type_id
system_type_name
max_length
precision
scale
collation_name
user_type_id
user_type_database
user_type_schema
user_type_name
assembly_qualified_type_name
xml_collection_id
xml_collection_database
xml_collection_schema
xml_collection_name
is_xml_document
is_case_sensitive
is_fixed_length_clr_type
source_server
source_database
source_schema
source_table
source_column
is_identity_column
is_part_of_unique_key
is_updateable
is_computed_column
is_sparse_column_set
ordinal_in_order_by_list
order_by_is_descending
order_by_list_length
error_number
error_severity
error_state
error_message
error_type
error_type_desc
You could get information about a stored procedure's parameters but, without executing it, SQL Server cannot tell you the structure of the dataset(s) returned by the stored procedure. Since executing a stored procedure can have side effects, ADO.NET doesn't provide a method for telling you what the result set(s) would look like were the stored procedure to be executed. Furthermore, the result set(s) might change depending on the parameters passed to the procedure when it is executed.
I am not getting your question clearly I think this would work with you
Select *
from sys.objects
where type='p' and name = (procedure name)
Replace your query with this and it will work fine
I've created various code generators that use the output of stored procs. In my experience, most procedures that SELECT anything output their schema just the same if you call them with null (DbNull.Value) as the value for all parameters. You can get the parameter list itself from system views, though I find it convenient to use INFORMATION_SCHEMA.PARAMETERS.
By executing the procedure in a transaction and always rolling back you can safely execute stuff even when you have no idea what the procedure does.
You'll probably need a basic GUI and allow the user to modify the parameters - or a config file or some other way to provide parameter values for specific procedures. A stored proc may produce output with different schemas depending on the parameters, though I haven't seen many that do.
App.config
<appSettings>
<add key="Schema_Name" value ="[dev]."/> <!-- use any one [dev]. or [dbo]. -->
</appSettings>
c# read Key
string schema_Name = Configuration["Schema_Name"].ToString();
Store Procedure
SqlConnection objConn = new SqlConnection(Connection);
objConn.Open();
SqlCommand cmd = new SqlCommand("Exec WLTCVarification", objConn);
cmd.Parameters.Add("#SchemaName", SqlDbType.Text);
cmd.Parameters["#Schema_Name"].Value = schema_Name; // dev or dbo;
rowsAmount = (string)cmd.ExecuteScalar();
objConn.Close();
c# Sql Query
SqlConnection objConn = new SqlConnection(Connection);
objConn.Open();
SqlCommand cmd = new SqlCommand("select * from " + schema_Name + "receive_agv_onlyerror, objConn);
rowsAmount = (string)cmd.ExecuteScalar();
objConn.Close();

Categories