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 });
Related
Why my code show this message
Data type mismatch in criteria expression.
The attribute Fine is in number datatype.
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
string cq = "select sum(Fine) from Studentbook where Student_ID='" + textsearch.Text + "'";
command.CommandText = cq;
int a = Convert.ToInt32(command.ExecuteScalar());
connection.Close();
MessageBox.Show(a.ToString(), "Your FINE is", MessageBoxButtons.OK);
Other than possible SQL Injection vulnerability; the said error could be because of the WHERE part in your query; where Student_ID is number and you are trying to compare it with string type data.
where Student_ID='" + textsearch.Text + "'"
Considering that your Student_ID is of INT or NUMBER type column change your code to be like below. Notice the use of parameterized query to avoid SQL Injection
string sql = "select sum(Fine) from Studentbook where Student_ID = #studentid";
SqlCommand command = new SqlCommand(sql, connection);
command.Parameters.AddWithValue("#studentid", Convert.ToInt32(textsearch.Text.Trim()));
The error is saying incorrect syntax near nchar this is what visual studio suggests
the error suggests Line 31:
An expression of non-boolean type specified in a context where a condition is expected, near 'Name'.
int temp = Convert.ToInt32(com.ExecuteScalar());
my code is below
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
conn.Open();
string checkuser = "select count(*) from [Table] where User Name=#User Name";
SqlCommand com = new SqlCommand(checkuser, conn);
com.Parameters.Add("#User Name", SqlDbType.NChar, 20).Value = TextBoxUN.Text;
int temp = Convert.ToInt32(com.ExecuteScalar());
if (temp == 1)
{
Response.Write(" USER ALREADY EXISTS ");
}
conn.Close();
}
}
If your database objects and parameter names you used with them are more than one word, you need to use them square brackets like [User Name]
Also use using statement to dispose your SqlConnection and SqlCommand.
using(SqlConnection conn = new SqlConnection(connString))
using(SqlCommand com = conn.CreateCommand())
{
com.CommandText = "select count(*) from [Table] where [User Name] = #UserName";
com.Parameters.Add("#UserName", SqlDbType.NChar, 20).Value = TextBoxUN.Text;
conn.Open();
int temp = Convert.ToInt32(com.ExecuteScalar());
}
As a best practice, don't use more than one word for your table or column names.
try that
string checkuser = "select count(*) from [Table] where [User Name]=#UserName"
SqlCommand com = new SqlCommand(checkuser, conn);
com.Parameters.Add("#UserName", SqlDbType.NChar, 20).Value = TextBoxUN.Text;
You should wrap column names in braces if it has whitespace in it. so the column name User Name should be places in square braces '[]', for the parameter name "#User Name", I don't think that it would accept it neither, you should remove the whitespace in parameter name also.
So,
Trying to write a very simple method to update a single column in a database. I keep getting a runtime error of "Syntax Error" near the commented line below
public void SaveStatus(string id, string step)
{
// assuming that there is only one matching student ID
connect = new SqlConnection(connectionString);
connect.Open();
dataSet = new DataSet();
string command = "SELECT * FROM tblSubmissions WHERE Id = " + id;
dataAdapter = new SqlDataAdapter(command, connect);
dataAdapter.Fill(dataSet, "tblSubmissions"); // syntax error near here
dataSet.Tables[0].Rows[0]["StatusID"] = step;
dataAdapter.Update(dataSet, "tblSubmissions");
dataAdapter.Dispose();
connect.Close();
connect.Dispose();
}
Hoping someone can point out the obvious problem I'm missing
The query should be "SELECT * FROM tblSubmissions WHERE Id = 'id_value' - you're missing the quotes around the id value.
Use a parametrised query instead of string concatenation to fix your problem and get rid of the SQL injection issue:
SqlCommand cmd = new SqlCommand("SELECT * FROM tblSubmissions WHERE Id = #id" , connect);
cmd.Parameters.Add("#id", SqlDbType.UniqueIdentifier);
cmd.Parameters["#id"].Value = id;
I have the public DataTable here and the code looks right, but its not returning anything, the OrderID is correct, the query itself is correct, its not returning anything...can anyone tell me why?
public DataTable get_OrderTransaction_Master_ByOrderID(Int64 orderID)
{
cn = new SqlConnection(objCommon.IpcConnectionString);
cn.Open();
string query = "select transactionID from dbo.OrderTransaction_Master where orderID = " + orderID;
SqlCommand queryCommand = new SqlCommand(query, cn);
SqlDataReader queryCommandReader = queryCommand.ExecuteReader();
DataTable dataTable = new DataTable();
dataTable.Load(queryCommandReader);
cn.Close();
return dataTable;
}
Caveat:This is a guess based on incomplete information:
Try this: Change query string and add the line to add the parameter.
string query = "select transactionID from dbo.OrderTransaction_Master where orderID = #OrderId";
SqlCommand queryCommand = new SqlCommand(query, cn);
queryCommand.Parameters.AddWithValue("#OrderId", orderID);
SqlDataReader queryCommandReader = queryCommand.ExecuteReader();
Explanation: Not only will this prevent SQL Injection, it will automatically assure that the OrderId is handled correctly.
You didn't specify what the data type is for the OrderId in the database. I'm guessing it may be non-numeric. (guid or varchar - I've seen databases that use nun-numeric IDs, so it's not inconceiveable.) If it's non-numeric you may be missing the quotes areound the value.
Example:
Where Id = 1
is NOT the same as
Where Id= '1'
Using a parameterized query will automagically fix this for you.
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.