Invalid object name even if it exists - c#

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

Related

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

Update only one column using ID in asp.net

I want to update only one column in my table by ID .
I don't have any error but this don't work, it won't update. I have ID column and 7 more columns.
SqlCommand cmd1 = new SqlCommand("update table set amount=#kol where ID=#id" , con);
cmd1.Parameters.AddWithValue("#id", textbox1.Text);
cmd1.Parameters.AddWithValue("#kol", textbox2.Text );
Is your table named "table" or is that just for the example here?
Because otherwise you properbly need to change "table" to whatever table your're trying to update. or surround it with [] if it is actually called "table"
Can you please check that you have commited your work , if there is no exception then that will be the reason
and if not put setautocommit(true) - java version
you can find it for c#
please check whether table name is correct and the table which you are verifying is correct
please give some other table name than table for good practice
As long as you have con.Open and ExecuteNonQuery and have the username/password and connectionstring right your code will work.
This will work after you change the connectionstring, if not the problem is sql server.
private void UpdateTable()
{
SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=YourDataBase;Persist Security Info=True;User ID=username;Password=pass");
SqlCommand cmd1 = new SqlCommand("update YourTable set amount=#kol where ID=#id", con);
cmd1.Parameters.AddWithValue("#id", textBox1.Text);
cmd1.Parameters.AddWithValue("#kol", textBox2.Text);
con.Open();
cmd1.ExecuteNonQuery();
}

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..>!!!!

Determining if user login already exists in database?

I am building a web application in asp.net using C#. I have the Form where the user should register and then can login. I am having a problem in making the web app know that the name which the user picks is either "already exists" or not. If it already exists it should not insert the same name and display a message saying "user name already exists". I have tried the SqlDataReader but no luck.
protected void Register_Button_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["BJ_Player_String"].ToString());
SqlCommand cmd = new SqlCommand();
SqlCommand cmd2 = new SqlCommand();
SqlDataReader data_reader;
String name = TextBox2.Text;
String date = TextBox3.Text;
try
{
conn.Open();
cmd = new SqlCommand("Insert into BJ_Player (Player_Name, D_O_B) Values (#Player_name, #D_O_B)", conn);
cmd = new SqlCommand("Select Player_Name from BJ_Player WHERE Player_Name = #Player_name", conn);
cmd.Parameters.Add("#Player_name", SqlDbType.NVarChar).Value = name;
cmd.Parameters.Add("#D_O_B", SqlDbType.Date).Value = date;
cmd.Connection = conn;
data_reader = cmd.ExecuteReader();
cmd.ExecuteNonQuery();
if (data_reader.HasRows)
{
lblPlayerNameExists.Visible = true;
}
else
{
// do nothing
}
}
Make Player_Name unique in database then it will give you exception when you try to insert. You have to use unique constraint.
You have to give command type also and check you assigned both queries to same cmd object
in your code you're inserting data in your DB and then you are examining that the name is the same or not.
first you should search the name in your DB and then if there isn't any record with that name ,you should add your record.
I usually do it in one of two ways:
Create stored procedure that will check for name uniqueness and insert new record if everything is ok. It should return status as numeric code that you will check.
Check for name uniqueness before saving it using as a part of validation process.
Using the merge statement may help with this. Merge performs insert, update, or delete operations on a target table based on the results of a join with a source table.
Basically it inserts when needed, and updates when needed. Often times referred to as an upsert. but it gets the job done.
Here is a link to a site explaining how to use merge. Looks like a good article.
http://www.kodyaz.com/articles/sql-server-2008-t-sql-merge-statement-example.aspx
If you would like to write a model function to do that then
Leave it for ajax check which is pretty similar to the second
method
Issue "Select username from DB-table" to retrieve
usernames then check the username input against them before
displaying a view to report a problem if any or showing a message to
tell the user that "this name is valid", for example.

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