Reading SQL Server database - c#

I need to read data from a SQL Server database. Something doesn't work with syntax of the table, which has Id as a primary key plus several items.
SqlConnection CON = new SqlConnection("Data Source = pc\\sqlexpress; Initial Catalog = dccDB; Integrated Security = True");
string strSQL = "SELECT Id Item" + "FROM [dbo.Table]";
SqlCommand cmd = new SqlCommand(strSQL, CON);
{
CON.Open();
MessageBox.Show("SQL DataBase dccDB.dbo is connected");
SqlDataReader reader = cmd.ExecuteReader(); (ERROR !!!)
while ( reader.Read() )
{
MessageBox.Show( reader["Id"].ToString(), reader["Item"].ToString());
}
reader.Close();
CON.Close();
}
There is a error message: ex.Message
Wrong syntax close to 'dbo.Table'.
Many thanks for your ideas.

You're missing a space in your SQL and using the brackets incorrectly. Columns need to be separated by commas. The line should be:
string strSQL = "SELECT Id, Item FROM [dbo].[Table]";

Have a space after Item in ur query, and separate dbo.table to [dbo].[table] like:
string strSQL = "SELECT Id, Item " + "FROM [dbo].[Table]";

There is no space between Item and From, replace your strSql line with following:
string strSQL = "SELECT Id Item " + "FROM [dbo.Table]";

Related

System.Data.SqlClient.SqlException: "Invalid column name 'e'." | Error with Database

Im using Database Data for my Project and when I type a letter in Textbox1, the application crashes with the error:
System.Data.SqlClient.SqlException: "Invalid column name 'e'."
Database name is Table with "Id" and "altitudes"
Id is a varchar and altitudes is a nchar.
Thats how I want it to work:
Typing a Name in name.Text, search for the name in the database and paste the assigned altitude in altitude.Text.
Altitudes are numbers, Names are Letters in the database.
Where's the error in my code? (Data Source is on purpose blank)
{
String source = #"Data Source=";
SqlConnection con = new SqlConnection(source);
con.Open();
String sqlSelectQuery = "SELECT * FROM [Table] WHERE ID ="+char.Parse(name.Text);
SqlCommand cmd = new SqlCommand(sqlSelectQuery, con);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
altitude.Text = (dr["altitudes"].ToString());
}
con.Close();
}
You should never concatenate inputs to create SQL. It is horribly brittle, and susceptible to SQL injection, and i18n/l10n problems (formatting of values). Lots of bad things.
The solution should always be: parameters.
For example:
const string sqlSelectQuery = "SELECT * FROM [Table] WHERE ID = #id";
using SqlCommand cmd = new SqlCommand(sqlSelectQuery, con);
cmd.Parameters.AddWithValue("#id", name.Text);
// Etc
Or more easily with a tool like Dapper:
var alt = con.QuerySingleOrDefault<string>(
"SELECT altitudes FROM [Table] WHERE ID = #id",
new { id = name.Text });

INSERT INTO Table (Column) VALUE (email)

I want to insert email in Table with only one column. I tried on 2 way. First time I tried with commandText and second time I tried with parapeters. But the both solution give me the same error.
System.Data.OleDb.OleDbException: 'Syntax error in INSERT INTO statement.'
I don't see any error in INSERT STATEMENT. Maybe the problem is in TABLE?
using (OleDbCommand cmd = new OleDbCommand())
{
cmd.Connection = conn;
cmd.CommandText = "SELECT COUNT (email) FROM [User] WHERE [email] LIKE '" + userEmail + "';";
conn.Open();
int count = Convert.ToInt32(cmd.ExecuteScalar()); // This passed
if (count == 0)
{
string query = #"INSERT INTO User (email) VALUES (#email)";
string cmdText= #"INSERT INTO User (email) VALUES ('"+userEmail+"')";
OleDbCommand command = new OleDbCommand(cmdText, conn);
// command.Parameters.AddWithValue("#email", "userEmail");
// command.CommandText = query;
command.ExecuteNonQuery(); // I GOT ERROR HERE
}
conn.Close();
}
User is a keyword. You should INSERT INTO [USER] instead
string cmdText= #"INSERT INTO User (email)) VALUES ('"+userEmail+"')";
you have one ')' too many after (email)

Doesn't work th SqlCommand with multiple queries

With one SELECT query, the code seems to add to the listbox correctly, but when I add another query, the listbox doesn't show anything anymore, and it seems that that rdr[3] does not exists (Contact has 3 columns and Numar_contact has one column (should't it be this one the rdr[3]?))
string connString = #"database=Agenda_db; Data Source=Marian-PC\SQLEXPRESS; Persist Security Info=false; Integrated Security=SSPI";
SqlConnection conn = new SqlConnection(connString);
try {
conn.Open();
SqlCommand cmd = new SqlCommand("SELECT * FROM Contact;"+ "SELECT * FROM Numar_contact", conn)
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
listBox1.Items.Add(rdr[0].ToString() + ' ' + rdr[1].ToString() + ' ' + rdr[2].ToString()+' '+ rdr[3].ToString());
}
rdr.Close();
Join your queries with a UNION. The way you've got it now, it'll return two results sets.
SELECT [col1], [col2] FROM Contact
UNION ALL
SELECT [col1], [col2] FROM Numar_contact
As DJ KRAZE pointed out in a comment, it might not be a bad idea to wrap this in a sproc or a TVF. But this will work too.
Edit:
I just learned via comments that the two tables are actually unrelated. In light of that, I'd be tempted to use two SqlCommands with two, distinct foreach loops. But if you're sold on this way,
SELECT id_contact, nume_contact, prenume_contact FROM Contact
UNION ALL
SELECT id_contact, numar, NULL FROM Numar_contact
This will align the data from the two tables, but where the second table doesn't have a [prenume_contact] it will select NULL. I might have mixed up the column positions here, since I don't really understand what those names are meant to represent.
Edit 2:
string connString = #"database=Agenda_db; Data Source=Marian-PC\SQLEXPRESS; Persist Security Info=false; Integrated Security=SSPI";
using (SqlConnection conn = new SqlConnection(connString))
{
try
{
conn.Open();
using (SqlCommand cmd = new SqlCommand("SELECT * FROM Contact", conn))
using (SqlDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
listBox1.Items.Add(rdr[0].ToString() + " " + rdr[1].ToString() + " " + rdr[2].ToString());
}
}
using (SqlCommand cmd2 = new SqlCommand("SELECT * FROM Numar_contact", conn))
using (SqlDataReader rdr2 = cmd.ExecuteReader())
{
while (rdr2.Read())
{
listBox1.Items.Add(rdr2[0].ToString() + " " + rdr2[1].ToString());
}
}
}
catch { }
}
Edit 3, thanks to insight from Scott Chamberlain:
On the other hand, you might want to perform a JOIN of some kind, most commonly an INNER JOIN. Note that this is an entirely different operation from any we've talked about before.
SELECT Contact.id_contact, Contact.nume_contact, Contact.prenume_contact, Numar_contact.numar
FROM Contact
INNER JOIN Numar_contact on Contact.id_contact = Numar_contact.id_contact
This will tie the two tables together, returning a record for each contact-numar_contact. Again, this is definitely not the same as doing a UNION. Make sure you're aware of the difference before you pick which you want.
Use this if your second table contains data that relates many-to-one to the first table.
Thanks to your comment, what you are wanting to do is JOIN the tables.
SELECT Contact.id_contact, nume_contact, prenume_contact, numar
FROM Contact
INNER JOIN Numar_contact on Contact.id_contact = Numar_contact.id_contact
That will combine the two tables in to four columns where id_contact matches in both tables.
You may want a INNER JOIN or a LEFT JOIN depending on if you want rows to show up only when there is a item in the 2nd table or show up anyway and just make the 4th column DBNull.Value.
Yes you can.
Here is an example from the MSDN I've modified to use your code - you need to move the reader to the Next ResultSet
string connString = #"database=Agenda_db; Data Source=Marian-PC\SQLEXPRESS; Persist Security Info=false; Integrated Security=SSPI";
SqlConnection conn = new SqlConnection(connString);
SqlCommand myCommand = new SqlCommand("SELECT * FROM Contact; SELECT * FROM Numar_contact", conn);
SqlDataReader myReader ;
int RecordCount=0;
try
{
myConnection.Open();
myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
//Write logic to process data for the first result.
RecordCount = RecordCount + 1;
}
MessageBox.Show("Total number of Contacts: " + RecordCount.ToString());
bool moreResults = myReader.NextResult(); // <<<<<<<<<<< MOVE TO NEXT RESULTSET
RecordCount = 0;
while (moreResults && myReader.Read())
{
//Write logic to process data for the second result.
RecordCount = RecordCount + 1;
}
MessageBox.Show("Total number from Numar_contacts: " + RecordCount.ToString());
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
conn.Close(); // Could be replaced with using statement too
}

SqlDataReader Execution error

i m trying to retrieve the Specialization ID from a table called Specializationtbl, using C# MSVS 2008 and the table includes SpecializationName and SpecializationID beside some other rows and my question is related to some error " No Data to present ", the command goes as bellow:
SqlCommand READSpecID = new SqlCommand("SELECT * FROM Specializationtbl WHERE SpecializationName='" + comboBox1.Text + "'" , DBcnction);
DBcnction.Open();
SqlDataReader ReadSpecID_ = READSpecID.ExecuteReader();
ReadSpecID_.Read();
int SpecID_ = Convert.ToInt16(ReadSpecID_["SpecID"].ToString());
DBcnction.Close();
i also tried to Select the "SpecID" instead of all the rows, but cant seem to seal the query correctly and keep receiving "No data present " error, any idea where am i making the mistake?
1) Try opening DBcnction before assigning the value to READSPecID
DBcnction.Open();
SqlCommand READSpecID = new SqlCommand("SELECT * FROM Specializationtbl WHERE SpecializationName='" + comboBox1.Text + "'" , DBcnction);
2) Run the command in SSMS:
SELECT * FROM Specializationtbl WHERE SpecializationName ='yourvalue'
and see if any results are returned
3) Check comboBox1.Text has a value in it
4) Validate the contents of comboBox1.Text (Or use paremetrised queries or a stored procedure) to ensure you do not become a victim of SQL Injection: http://en.wikipedia.org/wiki/SQL_injection
Refactor to solve your TWO problems:
Your SQL injection problem when building your SQL statement.
Use ExecuteScalar if you only need one value.
Implement using blocks.
string retVal;
using (var conn = new SqlConnection(SomeConnectionString))
using (var cmd = conn.CreateCommand())
{
cmd.CommandText = "SELECT SpecID FROM Specializationtbl WHERE SpecializationName= #Name";
cmd.Parameters.AddWithValue("#Name", comboBox1.Text);
conn.Open();
retVal = cmd.ExecuteScalar().ToString();
}
int specID = int.Parse(retVal);
If you really needed more than one value from your statement:
using (var conn = new SqlConnection(SomeConnectionString))
using (var cmd = conn.CreateCommand())
{
cmd.CommandText = "SELECT SpecID, Value2 FROM Specializationtbl WHERE SpecializationName= #Name";
cmd.Parameters.AddWithValue("#Name", comboBox1.Text);
conn.Open();
var dr = cmd.ExecuteReader();
while (dr.Read())
{
Customer c = new Customer {
ID = dr["SpecID"].ToString(),
Value = dr["Value2"].ToString(),
};
}
}
Need to first test if there are any rows. I suspect the query is returning zero rows.
if (ReadSpecID_.HasRows)
{
ReadSpecID_.Read();
}

SQL query from C#

I am trying to query SQL Server database from C#
I have class
Class_A
{
public fetch((string name, string last_name))
{
SqlConnection conn = null;
double val = 0;
string server = "123.444.22.sss";
string dbase = "xyz";
string userid = "cnsk";
string password = "xxxxxx";
string connection = "Data Source=" + server + ";Initial Catalog=" + dbase
+ ";User ID=" + userid + ";Password=" + password;
conn = new SqlConnection(connection);
try
{
conn.Open();
}
catch(Exception)
{
string e = "Database error contact administrator";
MessageBox.Show(e, "Error!");
}
try
{
SqlDataReader myReader = null;
SqlCommand myCommand = new SqlCommand("select * from table where NAME"
+ " = name and LAST_NAME = last_name", conn);
myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
//do something
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
return (0);
}
}
There is a problem in my query.
When I give normal query "select * from table" --- this gives me perfect results.
But when I try to give where condition it gives me error. Any suggestions, to fix this?
Thanks.
Use a parameterised query, and more usings, and stop with the generic exceptions.
something like this where somName and SomeLastName are the values that you wan t to query for.
String sql = "Select * From SomeTable Where [Name] = #Name and [Last_Name] = #LastName";
try
{
using(SqlConnection conn = new SqlConnection(connection))
{
conn.Open();
using( SqlCommand command = new SqlCommand(sql,conn))
{
command.Parameters.Add(new SqlParameter("Name", DbType.String,someName));
command.Parameters.Add(new SqlParameter("LastName", DbType.String,someLastName));
using(IDataReader myReader = command.ExecuteReader())
{
while (myReader.Read())
{
//do something
}
}
}
}
return 0; // Huh?
}
catch(SqlException sex)
{
Console.Writeline(String.Format("Error - {0}\r\n{1}",sex.Message, sex.StackTace))
}
NB not checked might be a silly in it
⚠️ WARNING This answer contains a SQL injection security vulnerability. Do not use it. Consider using a parameterized query instead, as described in some of the other answers to this question (e.g. Tony Hopkinson's answer).
Try adding quotes around the values in the where clause like this:
select * from table where NAME = 'name' and LAST_NAME = 'last_name'
In your case where you are using variables you need to add the quotes and then concatenate the values of the variables into the string. Or you could use String.Format like this:
var sql = String.Format("select * from table where [NAME] = '{0}' and LAST_NAME = '{1}'", name, last_name);
SqlCommand myCommand = new SqlCommand(sql);
Try
select * from table where NAME = 'name' and LAST_NAME = 'last_name'
instead of
select * from table where NAME = name and LAST_NAME = last_name
Edit:
If name and last_name are your parameters then try this:
SqlCommand myCommand = new SqlCommand("select * from table where NAME = #name and LAST_NAME = #last_name", conn);
myCommand.Parameters.AddWithValue( "#name", name );
myCommand.Parameters.AddWithValue( "#last_name", last_name );
Using parameterized commands means that you are invulnerable to a potential huge security hole - sql injection which is possible when command text is manually concatenated.
The text needs to be quoted as others have said--but that's not really the right answer here. Even without malice you're going to run into trouble with the Irish here, look what happens when you try to look for Mr. O'Neill. Use parameters instead.

Categories

Resources