I have a function which would populate a datatable with the contents of a table. But its showing an annoying invalid column name error with the value I give in the WHERE clause.
public static DataTable GetRequests(string empid)
{
DataTable dt = new DataTable();
string strConnection = ConfigurationManager.AppSettings["connStr"];
using (SqlConnection connection = new SqlConnection(strConnection))
{
connection.Open();
SqlCommand sqlcmd = new SqlCommand();
SqlDataAdapter sAdap = new SqlDataAdapter();
sqlcmd.Connection = connection;
sqlcmd.CommandType = System.Data.CommandType.Text;
sqlcmd.CommandText = "Select * from requests Where emp_id=P001";
sAdap.SelectCommand = sqlcmd;
sAdap.Fill(dt);
}
return dt;
}
Now with this i am getting the error at
sAdap.fill
and the error is
invalid column name P001
I'm stumped at this. Any ideas why I'm facing this issue?
If it's a string constant, surround it with single quotes. 'P001' or better still, paramaratise it.
You need string delimiters around the value. Change the line to:
sqlcmd.CommandText = "Select * from requests Where emp_id='P001'";
with the single quotes around P001 and you should be fine.
You need to use single quote.
where emp_id='P001'
It looks like your P001 data is a string type. Try quoting it with single quotes before feeding it in as an sql string.
sqlcmd.CommandText = "Select * from requests Where emp_id='P001'";
If that doesn't work (though it should) you can try the like statement as in:
sqlcmd.CommandText = "Select * from requests Where emp_id like 'P001'";
You need to surround your (apparrently) text criteria with single quotes:
sqlcmd.CommandText = "Select * from requests Where emp_id = 'P001'";
Related
It gives an error when I run this code, help me to resolve this error.
Incorrect syntax near '='.
my question about what kind error is this.?
namespace SqlCommandBuilders
{
public partial class WebForm1: System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
String CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
SqlConnection con = new SqlConnection(CS);
string sqlQuery = "Select * from tblStudents where ID = "+txtStudentID.Text;
SqlDataAdapter da = new SqlDataAdapter(sqlQuery, con);
DataSet ds = new DataSet();
da.Fill(ds, "Students");
ViewState["SQL_QUERY"] = sqlQuery;
ViewState["DATASET"] = ds;
if(ds.Tables["Students"].Rows.Count > 0)
{
DataRow dr = ds.Tables["Students"].Rows[0];
txtStudentID.Text = dr["Name"].ToString();
txtTotalMarks.Text = dr["TotalMarks"].ToString();
ddlGender.SelectedValue = dr["Gender"].ToString();
}
else
{
lblStatus.ForeColor= System.Drawing.Color.Red;
lblStatus.Text = "No Student Record with ID =" + txtStudentID.Text;
}
}
}
}
Think about the string you're creating for a moment. Suppose txtStudentID.Text is the string Joe. You'd be creating Select * from tblStudents where ID = Joe which is obviously incorrect. Joe needs quotes around it.
But, don't just put quotes around it. Here's why:
The correct thing to do is use a parameterized statement, as described on here the site linked above. Applying their example to your code, we'd get something like:
SqlCommand sqlQuery = new SqlCommand("Select * from tblStudents where ID = #username", con);
sqlQuery.Parameters.AddWithValue("#username", txtStudentID.Text);
...but I don't know what your ViewState thing is, so can't help you apply it there.
SQL commands that use text input by users should almost ALWAYS use parameterized queries to avoid SQL injection attacks and syntax errors, and it's also good to get in the habit of wrapping disposable objects (like database connections) in using statements:
DataSet ds = new DataSet();
using(SqlConnection con = new SqlConnection(CS)) {
string sqlQuery = "Select * from tblStudents where ID = #studentId";
using(SqlDataAdapter da = new SqlDataAdapter(sqlQuery, con)) {
da.SelectCommand.Parameters.Add("#studentId", SqlDbType.VarChar)
.Value = txtStudentID.Text;
da.Fill(ds, "Students");
}
}
A couple things here.
SQL parameters should always be used in cases such as this.
Also, Is Student ID a text field in the database or a number?
If its a numeric, where is the textbox being initialized? The page_load is one of the first things that happen, and since you are running this on all page_loads (even the first time), if its an empty string, it'll definitely crash regardless of whether you use parameters or not, because an empty string cannot be converted to a number.
I have a table Registration with many columns. I need to get customer_id and put that value into a variable for use that in a session for moving & use between ASP Webforms. How can I do this?
You can use ExecuteScalar method to get single column value. Below is a very basic example of how to get single column value.
string connectionString = ConfigurationManager.ConnectionStrings["YourConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand("select Customer_id from Registration", con);
con.Open();
string id = cmd.ExecuteScalar().ToString();
}
Here is how you can store the value in session
Session["CustomerID"] = id;
And here is how you can retrieve the value on second page
int ID = 0;
int.TryParse((string)Session["CustomerID"], out ID);
I have a table containing name, surname and email. I want to retrieve them from the table and so i write:
if (LoginAs.SelectedValue == "Administrator")
{
string result;
string query = "Select * from AdminTable where ID='"+ idBox.Text +"'";
cmd1 = new SqlCommand(query, con);
result = Convert.ToString(cmd1.ExecuteScalar());
Response.Redirect("Admin.aspx");
//Admin user = new Admin(idBox.Text, "Active", mail, firstName, LastName, passwordBox.Text);
}
The problem is, it only returns the name field of the specified row even though i wrote "Select *". What is wrong here?
ExecuteScalar returns just the first column of the first row, and ignores the rest.
So you should use ExecuteReader method. An example from MSDN:
using (SqlConnection connection = new SqlConnection(
connectionString))
{
connection.Open();
SqlCommand command = new SqlCommand(queryString, connection);
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
Console.WriteLine(String.Format("{0}", reader[0]));
}
}
Note that the while (reader.Read()) checks whether your query returned (more) results and positions the cursor on the next record, that you can then read. This example prints the first column's value.
The using statement makes sure the connection is closed after use, whatever happens.
Also, don't build your query directly with input from the user (such as the value of a TextBox), use parameters instead to prevent SQL injection attacks.
You must try ExecuteReader() instead of using ExecuteScalar()
ExecuteScaler is used in situation where we have to read a single value.eg:
select count(*) from tablename.
while
ExecuteReader is used for any result set with multiple rows/columns
(e.g., SELECT * from TableName)
Sample code:
string myQuery="Select * from AdminTable where ID=#myid";
SqlCommand cmd=new SqlCommand(myQuery,conn);
cmd.Parameters.AddWithValue("#myid", value);
conn.Open();
SqlDataReader dreader;
dreader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
while (dreader.Read())
{
string Value1= dreader["COl1"].ToString();
string Value2= dreader["COl2"].ToString();
}
dreader.Close();
Always use parameterized Query
You may try cmd1.ExecuteReader() instead.
I want to use variable name as column name in ASP.NET column name.
I'm getting the following error:
Incorrect syntax near 'February'.
The code is
SqlConnection MyConn = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=E:\apptitude\projects\database\App_Data\Database.mdf;Integrated Security=True;User Instance=True");
MyConn.Open();
int i,n=5;
String[] month=new String[12]{"January","February","March","April","May","June","July","August","September","Octomber","November","December"};
int day = DateTime.Now.Day;
int mon= DateTime.Now.Month;
Label1.Text = day.ToString();
if (day==1)
{
//for(i=1;i<=n;i++)
//{
//Label1.Text = "hi";
int j = 1;
SqlCommand cmd = new SqlCommand();
cmd.Connection = MyConn;
cmd.CommandText = "update Yearly_data set **'"+month[mon]+"'=20";**
i = cmd.ExecuteNonQuery();
Label1.Text = i.ToString();
}
You don't need to enclose column names in single quotes ('); hence this:
update Yearly_data set 'February'=20
Should be written as
update Yearly_data set February=20
If you change your code to the below, it will work:
cmd.CommandText = "update Yearly_data set "+month[mon]+"=20";
However, note that building Dynamic SQL statements is something that should be carefully done as not to risk your app on a SQL Injection attack.
If every month of the year is a ColumnName in Yearly_data then change your line of code to:
cmd.CommandText = "update Yearly_data set ["+month[mon]+"]=20";
In addition to the answers already given, the framework provides a way to get the name of the month using the DateTimeFormatInfo.GetMonthName function.
static string GetMonthName(DateTime sourceDate)
{
var dateFormatInfo = new DateTimeFormatInfo();
return dateFormatInfo.GetMonthName(sourceDate.Month);
}
cmd.CommandText = String.Format("update Yearly_data set {0} = 20", GetMonthName(DateTime.Now));
Trying to do a recordset, I just want one column of data, but this code is giving me an error.. I'm an ASP.NET newb, can anyone help?:
System.Data.SqlClient.SqlException: Invalid column name
'CustomerName'.
using (SqlConnection con = new SqlConnection(DB.GetDBConn()))
{
con.Open();
using (IDataReader dr = DB.GetRS("select CustomerName from Customer where CustomerID=" + Customer.CustomerID, con))
{
string CustomerName = "CustomerName";
}
}
String EncCustomerName = Encrypt(CustomerName.Replace(".", "").Replace("-", ""),"1");
Question #2: How do I bind the database content to the CustomerName string? It seems like its only returning "CustomerName" as the value for CustomerName string.. I would like it to return the database data for CustomerName string.. Help?
Suggested to use a ExecuteScalar, so i modified the request to this
using (var con = new SqlConnection(DB.GetDBConn()))
using (var cmdContrib = new SqlCommand("SELECT CustomerName FROM Customer WHERE CustomerID=" + ThisCustomer.CustomerID, con))
{
con.Open();
string CustomerName = cmdContrib.ExecuteScalar();
}
And i Get this error:
"string CustomerName = cmdCust.ExecuteScalar();"
CS0266: Cannot implicitly convert type 'object' to 'string'. An explicit conversion exists (are you missing a cast?)
To answer your second question:
// Set it here so you can access it outside the scope of the using statement
string CustomerName = "";
using (SqlConnection con = new SqlConnection(DB.GetDBConn()))
{
con.Open();
using (IDataReader dr = DB.GetRS("select CustomerName from Customer where CustomerID=" + Customer.CustomerID, con))
{
while (dr.Read())
CustomerName = dr["CustomerName"].ToString();
}
}
}
If you're sure you'll only get one CustomerName result, using a DataReader is a bit of an overkill.
SqlCommand.ExecuteScalar Example
string CustomerName = "";
using (SqlConnection con = new SqlConnection(DB.GetDBConn()))
{
SqlCommand cmd = new SqlCommand("SELECT CustomerName FROM Customer WHERE CustomerID = " + Customer.CustomerID, con);
cmd.CommandType = CommandType.Text;
con.Open();
CustomerName = Convert.ToString(cmd.ExecuteScalar());
}
SqlCommand.ExecuteScalar Method
Additional Info
ExecuteScalar returns an object, so you'll need to convert the returned value to the proper type (in this case, string).
Also, you should declare your CustomerName value outside of the using blocks (as I did in my example) - otherwise it will be scoped to the using blocks and not available outside of them.
It means that either CustomerName or CustomerID is not a valid column within your database. Check your table again.
Make sure you are trying to connect correct database.
See CustomerName column should be in Customer table. check spelling also
First, debug and check the value of:
DB.GetDBConn()
You will verify that you are going to the same in Studio as you are in the program.
I think it is the spelling somewhere between the db and your code.
Once you get past the error, you need to fix this:
{
string CustomerName = "CustomerName";
}
You are not accessing the reader, try some kind of tutorial for that stuff.
Try doing a select * from customer where ... and put a breakpoint on your using datareader statement. Then use quick-watch on the datareader object to investigate the columns exposed in the recordset.
Or you could run the select statement on your db of choice to ensure that the column name is the same.
I agree with Madhur above, your column name is not spelled correctly. Or you are not connecting to the correct db.
Hope this helps