SqlCommand Select Command Aliases - c#

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());

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();

Invalid object name even if it exists

Here is my code:
InitializeComponent();
SqlConnection myConnection = new SqlConnection("data source = DESKTOP-77FA1JE;" +
"user id = DESKTOP-77FA1JE\\Chanloi" +
"initial catalog = TransactionProcessingSystem;" +
"integrated security = SSPI");
myConnection.Open();
SqlCommand myCommand = new SqlCommand("select * from UserAccounts", myConnection);
SqlDataReader myReader = myCommand.ExecuteReader();
BindingSource mySource = new BindingSource();
mySource.DataSource = myReader;
dataGridView1.DataSource = mySource;
myConnection.Close();
I get this error:
System.Data.SqlClient.SqlException: 'Invalid object name 'UserAccounts'.'
Very simple - You do not have a table called UserAccounts in your database.
Please try dbo.UserAccounts
In Such a Case What I Usually Do Is Run This Statment
select name from sys.tables
sys.Tables is a System View That Has info About The Existing Tables In Your Db , This Way You Can Check If The Table Already Exists or U Misspelled It's Name or Existed By Another Name , and Even But an if Condition To Execute Your Logic Only If This Table Exists
Also as Other Have Said it's A Good Practice To Put Column Names Between a [] Brackets , and Call It By Schema Name like dbo.MyTable
try this:
select * from dbo.[UserAccounts]
It's pretty straightforward. It's telling you that there is no UserAccounts table on your database. You can try dbo.UserAccounts, but if it fails, check your database first and also make sure you're connecting to right database.
Hope it helps!
The above exception says that the table UserAccounts does not exist in your database you are connected through your connection string
if the table is created do a local refresh cahce from Edit section and then intellisense and then refresh lcoal cache

Syntax error while trying to fetch data from MySql

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.

Getting "Invalid Column Name " Sql Exception in the following code

I am trying to pass both Column name and the Value to be checked in the code at runtime. However I am getting an "Invalid Column Name " exception.
The code is as follows :
string temp = TextBox1.Text.ToString();
SqlConnection con = new SqlConnection("data source=.\\SQLEXPRESS;AttachDbFilename=C:\\Users\\Sagar\\Documents\\Test.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
SqlCommand com = new SqlCommand("Select * from Employee Where #field = Sagar", con);
com.Parameters.AddWithValue("#field", DropDownList1.SelectedValue.ToString());
//com.Parameters.AddWithValue("#value", temp);
SqlDataAdapter da = new SqlDataAdapter(com);
con.Open();
SqlDataReader reader = com.ExecuteReader();
GridView1.DataSource = reader;
GridView1.DataBind();
The message says that there is no column named 'Sagar' in the table. Is there such a column? Things would be easier if you showed us the table schema instead of having us guess from the error message.
It is not possible to parameterize column names using SqlParameter in C#. This has been discussed here multiple times.
What's happening with the query the way Vidhya Sagar Reddy is doing it, is the following. He assumes that the following query
Select * from Employee Where #field = 'Sagar'
is replaced by this query when setting "Name" as the value for the #field parameter:
Select * from Employee Where Name = 'Sagar'
This, however, is wrong! What's happening is that the #field parameter is replaced as follows:
Select * from Employee Where 'Name' = 'Sagar'
This returns no results, as the WHERE clause is always false. Of course, if you use the field name Sagar, this akways returns true, as the statement then reads:
Select * from Employee Where 'Sagar' = 'Sagar'
Here's an easy test to prove what I've said above. Use the following statement to set the #field parameter (supposed, there's no column named eirghoerihgoh in the table):
com.Parameters.AddWithValue("#field", "eirghoerihgoh");
If the query executes correctly (maybe not returning any results), the above is correct. If it was not correct, an exception should be thrown about the eirghoerihgoh column not being present.
Thank you Vidhya Sagar Reddy for proving my point. By using this line
com.Parameters.AddWithValue("#field", "eirghoerihgoh");
you say you didn't get any results, but you also didn't get an exception. However, if the statement really had been changed to
Select * from Employee Where eirghoerihgoh = 'Sagar'
there had to be an exception saying that there was no column named eirghoerihgoh. As you didn't get that exception, there's only one possible explanation: The statement was changed to
Select * from Employee Where 'eirghoerihgoh' = 'Sagar'
and this executes, but doesn't return results, as the condition is always false.
Instead you can make your code this way, which works perfectly:
"Select * from Employee Where "+DropDownList1.SelectedValue.ToString()+" =
'Sagar'" – Vidhya Sagar Reddy
The reason for that is quite simple, the value that are to be specified in SQL should be in single quotes and this is a simple mistake by the way..!!!!
SqlCommand com = new SqlCommand("Select * from Employee Where #field = 'Sagar'", con);
And even change the parameter to "field" in the following line and not "#field"..!!
com.Parameters.AddWithValue("field", DropDownList1.SelectedValue.ToString());
This is working..>!!!!

SQL connection string for microsoft access 2010 .accdb

I am doing a simple login form using winforms and access 2010 database (.accdb) in C#.
I have the following code and it seems that the connection string is wrong. I have tried searching and found that .Jet is for access 07?? but this doesnt seem to work too.
i am an amateur at databases (code referred from msdn). I am having trouble understand which should i use for this example too.
access table name: haha
ID (PK) | password
-----------------------
1 | testing
System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\BC207\test.accdb");
System.Data.SqlClient.SqlCommand comm = new System.Data.SqlClient.SqlCommand();
comm.CommandText = "SELECT HAHA(*) FROM password";
comm.CommandType = CommandType.Text;
comm.Connection = conn;
conn.Open();
Object returnValue = comm.ExecuteScalar();
conn.Close();
MessageBox.Show((string)returnValue);
edited: the table's name is password, and the field that i want to get the value is ID.
SQL statement i wrote it as : SELECT ID FROM password
and yes, only one record in only one field in the table as the primary key.
anyway the problem is that the program hangs upon execution on the first line
-> Keyword not supported: 'provider'.
so i figured that I have a wrong connection string..
For Acces databases (.mdb, .accdb, etc...), you want to use OleDbConnection, not SqlConnection (SQL Server), like this:
conn = new System.Data.OleDb.OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\BC207\test.accdb")
Edit: as pointed out, for access OleDbConnection should be used, not SqlConnection...
you can use a much more compact way and also be sure connection is closed and disposed in any possible case even when exceptions are thrown, by using the using statements:
your query text was also, probably wrong as others have suggested...
using (var conn = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\BC207\test.accdb"))
using (var comm = conn.CreateCommand())
{
comm.CommandText = "SELECT password FROM HAHA";
comm.CommandType = CommandType.Text;
conn.Open();
var returnValue = comm.ExecuteScalar();
MessageBox.Show(returnValue.ToString());
}
Edit: are you sure the table HAHA only contains one row? Because the ExecuteScalar returns only one value, if you want to get 1 column but from many records you could use a DataReader or a DataSet...
comm.CommandText = "SELECT HAHA(*) FROM password";
It´s wrong.
"SELECT password FROM HAHA"
Your SQL statement should be,
SELECT * from HAHA
OR
SELECT [Password] From HAHA
EDIT:
You should change the ConnectionString.

Categories