Exception Details: System.Data.SqlClient.SqlException: Invalid column name 'PRC0000001' - c#

i keep getting this error, i dont know why, im still new to c#. kindly help me figure this out please. i have two dropdownlist that would populate data based on first dropdownlist selected value.
when i select a value on the first dropdownlist, i get that error..
here is my code..
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//read sql server connection string from web.config file
string constring = ConfigurationManager.ConnectionStrings["AccreString"].ConnectionString;
SqlConnection conn = new SqlConnection(constring);
DataTable dt = new DataTable("emed_province");
using (conn)
{
conn.Open();
SqlCommand comm = new SqlCommand("SELECT * FROM emed_province ORDER BY PROVINCE_NAME ASC", conn);
SqlDataAdapter adptr = new SqlDataAdapter(comm);
adptr.Fill(dt);
}
ddlProvince.DataSource = dt;
ddlProvince.DataTextField = "PROVINCE_NAME";
ddlProvince.DataValueField = "PROVINCE_CODE";
ddlProvince.DataBind();
}
}
protected void ddlProvince_SelectedIndexChanged(object sender, EventArgs e)
{
string constring = ConfigurationManager.ConnectionStrings["AccreString"].ConnectionString;
SqlConnection conn = new SqlConnection(constring);
DataTable dt = new DataTable("emed_province");
using (conn)
{
conn.Open();
SqlCommand comm = new SqlCommand("SELECT CITY_NAME FROM emed_city WHERE PROVINCE_CODE ="+ddlProvince.SelectedValue, conn);
SqlDataAdapter adptr = new SqlDataAdapter(comm);
adptr.Fill(dt);
}
ddlCity.DataSource = dt;
ddlCity.DataTextField = "CITY_NAME";
ddlCity.DataValueField = "CITY_CODE";
ddlProvince.DataBind();
}
}

It happens because you passed the raw value without quotes, so the database thought you mean field name.
Avoid this all mess by using Parameters:
using (conn)
{
conn.Open();
SqlCommand comm = new SqlCommand("SELECT CITY_NAME FROM emed_city WHERE PROVINCE_CODE=#pcode", conn);
comm.Parameters.AddWithValue("#pcode", ddlProvince.SelectedValue);
SqlDataAdapter adptr = new SqlDataAdapter(comm);
adptr.Fill(dt);
}

This answer is an alternative approach, when using Parameters isn't viable.
The SQL interpreter is confusing values with database objects.
You can save the interpreter from confusion by making your SQL statement more explicit. Surround columns and table names with [ square brackets and wrap any values in single quotes.
using (conn)
{
var whereValue = "'"+ddlProvince.SelectedValue+"'";//wrap in single quotes
conn.Open();
SqlCommand comm = new SqlCommand("SELECT [CITY_NAME] FROM [emed_city] WHERE [PROVINCE_CODE] = "+whereValue;
SqlDataAdapter adptr = new SqlDataAdapter(comm);
adptr.Fill(dt);
}
The square brackets explicitly state to the SQL Intepreter that it is dealing with a database object. The single quotes inform the interpreter it is dealing with a value.
Now the interpreter won't mistake your value for a column name.

Related

How to record count from ASP.NET using stored procedure?

I am trying to output the number of depositors which has a total of 5 but when I run the program it outputs only 1. I used stored procedure for this matter. I think something is missing when in the codes below and I don't know. I tried my best to search on the internet.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
CountAllUsers();
}
}
protected void CountAllUsers()
{
using (MySqlConnection mycon = new MySqlConnection(constring))
{
mycon.Open();
MySqlCommand cmd = new MySqlCommand("countallusers", mycon);
cmd.CommandType = CommandType.StoredProcedure;
MySqlDataAdapter adx = new MySqlDataAdapter(cmd);
DataSet ds= new DataSet();
adx.Fill(ds);
mycon.Close();
lblDepositors.Text = ds.Tables[0].Rows.Count.ToString();
}
You can use ExecuteScalar to do the query for counting the number of records. Replace TABLE_NAME with your table.
FYI, you don't have to call mycon.Close();, as you apply using statement, when it ends, it will dispose the connection automatically.
Updated:
Added using block for MySqlCommand for Disposable best practice as suggested by #Dai.
protected void CountAllUsers()
{
using (MySqlConnection mycon = new MySqlConnection(constring))
{
using (MySqlCommand cmd = new MySqlCommand("SELECT COUNT(*) FROM TABLE_NAME", mycon))
{
cmd.CommandType = CommandType.Text;
mycon.Open();
var count = Convert.ToInt32(cmd.ExecuteScalar());
lblDepositors.Text = count.ToString();
}
}
}
MySqlCommand.ExecuteScalar Method
ExecuteScalar method to retrieve a single value (for example, an aggregate value) from a database.
I already solved. Thanks!
protected void CountAllUsers()
{
using (MySqlConnection mycon = new MySqlConnection(constring))
{
mycon.Open();
MySqlCommand cmd = new MySqlCommand("SELECT COUNT(id) as count from depositors_tbl", mycon);
MySqlDataAdapter ada = new MySqlDataAdapter();
DataSet dt = new DataSet();
ada.SelectCommand = cmd;
ada.Fill(dt);
mycon.Close();
lblDepositors.Text = dt.Tables[0].Rows[0]["count"].ToString();
}
}

How to convert selected date to string and view on DataGrid

I'm trying to search for data between two dates and show on the datagrid. However I'm getting an error says that toString is unable to convert the selected date to string.
private void searchButton_Click(object sender, RoutedEventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source = xmsql04.australiaeast.cloudapp.azure.com,6302 ;Initial Catalog=DAD_TruckRental_RGM;Persist Security Info=True;User ID=xxxxxx;Password=xxxxxx");
SqlDataAdapter sda = new SqlDataAdapter("SELECT RentalId,TruckId,CustomerID,TotalPrice,RentDate,ReturnDueDate FROM TruckRental where JoiningDate between'"+fromText.SelectedDate.Value.ToString("MM/DD/YYYY")+"'AND'"+toText1.SelectedDate.Value.ToString("MM/DD/YYYY")+"'", con);
DataSet ds = new DataSet();
sda.Fill(ds, "TruckRental");
gridView2.ItemsSource = ds.DefaultViewManager;
}
UPDATE:
I have changed my code and have gotten rid of the error. However, no data is showing on in the grid, only an empty row. Would anyone know why that is?
string sqlStr = "SELECT RentalId,TruckId,CustomerID,TotalPrice,RentDate,ReturnDueDate FROM TruckRental where RentDate between #fromDT AND #toDT";
string connStr = #"Data Source = xmsql04.australiaeast.cloudapp.azure.com,6302 ;Initial Catalog=DAD_TruckRental_RGM;Persist Security Info=True;User ID=xxxxxx;Password=xxxxxx";
using (SqlConnection con = new SqlConnection(connStr))
using (SqlDataAdapter sda = new SqlDataAdapter(sqlStr, con))
{
sda.SelectCommand.Parameters.Add(new SqlParameter("#toDT", SqlDbType.DateTime)).Value = toText1.SelectedDate.Value;
sda.SelectCommand.Parameters.Add(new SqlParameter("#fromDT", SqlDbType.DateTime)).Value = fromText.SelectedDate.Value;
DataSet ds = new DataSet();
con.Open();
sda.Fill(ds, "TruckRental");
gridView2.ItemsSource = ds.DefaultViewManager;
}
There are some issues in your code.
Your con connection string didn't' open when you use Fill method, so you can't execute the SQL statement.
Your code has a SQL-Injection problem, I would suggest you use parameters instead of connected SQL statement string, make sure your parameter data type size as same as your table schema.
You didn't return the resource when you finish you have executed your SQL statement, I would use using statement because the purpose of Using statement is that when control will reach the end of using it will dispose that object of using block and free up memory. its purpose is not only for auto connection close, basically it will dispose of the connection object and obviously, the connection also closed due to it.
using SqlParameter class to make it.
private void searchButton_Click(object sender, RoutedEventArgs e)
{
string sqlStr = "SELECT RentalId,TruckId,CustomerID,TotalPrice,RentDate,ReturnDueDate FROM TruckRental where JoiningDate between #fromDt AND #toDt";
string connStr = #"Data Source = xmsql04.australiaeast.cloudapp.azure.com,6302 ;Initial Catalog=DAD_TruckRental_RGM;Persist Security Info=True;User ID=DDQ4_Melveena;Password=xxxxx";
using (SqlConnection con = new SqlConnection(connStr))
using (SqlDataAdapter sda = new SqlDataAdapter(sqlStr, con))
{
sda.SelectCommand.Parameters.Add(new SqlParameter("#toDt", SqlDbType.DateTime)).Value = toText1.SelectedDate.Value;
sda.SelectCommand.Parameters.Add(new SqlParameter("#fromDt", SqlDbType.DateTime)).Value = fromText.SelectedDate.Value;
DataSet ds = new DataSet();
con.Open();
sda.Fill(ds, "TruckRental");
gridView2.ItemsSource = ds.DefaultViewManager;
}
}

SQLConnection bringing data to TextBox

I know this looks really simple but i've been looking for an answer for hours with no luck.
I want to fill my row values into a bunch of textboxes. How can I specify that [CompanyName] is going to be used by the companyName textbox? Please keep it as simple as possible (beginner level).
string customerUniqueID = "test";
string constr = ConfigurationManager.ConnectionStrings["SQLConnection"].ToString(); // connection string
SqlConnection con = new SqlConnection(constr);
con.Open();
SqlCommand com = new SqlCommand("SELECT * FROM [Customers] WHERE [UniqueID] = #UniqueID", con); // table name
com.Parameters.Add("#UniqueID", SqlDbType.Int);
com.Parameters["#UniqueID"].Value = customerUniqueID;
SqlDataAdapter da = new SqlDataAdapter(com);
DataSet ds = new DataSet();
companyName.Text = ?????????
string customerUniqueID = "test";
string constr = ConfigurationManager.ConnectionStrings["SQLConnection"].ToString(); // connection string
SqlConnection con = new SqlConnection(constr);
con.Open();
SqlCommand com = new SqlCommand("SELECT * FROM [Customers] WHERE [UniqueID] = #UniqueID", con); // table name
com.Parameters.Add("#UniqueID", SqlDbType.Int);
com.Parameters["#UniqueID"].Value = customerUniqueID;
SqlDataAdapter da = new SqlDataAdapter(com);
DataSet ds = new DataSet();
da.Fill(ds, "Customers");
companyName.Text = ds.Tables[0].Rows[0]["CompanyName"].ToString();
I will recommend some changes in your code:
Your sql query returning result from one set, so you can use DataTabe instead of DataSet.
To fill results from DB to your DataTable you can use SqlAdapter.Fill() method.
Use Field() generic method (more examples of Field()) to get values from your DataTable.
Use using blocks for disposable objects, or at least make sure you've closed them after.
There is no need of con.Open() to open connection when using Fill() method, because from MSDN:
The Fill method implicitly opens the Connection that the DataAdapter is using if it finds that the connection is not already open. If Fill opened the connection, it will also close the connection when Fill is finished. This can simplify your code when dealing with a single operation such as a Fill or an Update.
string customerUniqueID = "test";
string constr = ConfigurationManager.ConnectionStrings["SQLConnection"].ToString(); // connection string
using(SqlConnection con = new SqlConnection(constr))
{
SqlCommand com = con.CreateCommand();
com.CommandText = "SELECT * FROM [Customers] WHERE [UniqueID] = #UniqueID";
com.Parameters.Add("#UniqueID", SqlDbType.Int);
com.Parameters["#UniqueID"].Value = customerUniqueID;
using(SqlDataAdapter da = new SqlDataAdapter(com))
{
DataTable dt = new DataTable();
da.Fill(dt);
companyName.Text = dt.Rows[0].Field<string>("CompanyName");
}
}
Please feel free to comment, if I missed something.

How to get one field in oledb c# program based on the value of textbox?

I get Oledb exception
private void Form5_Load(object sender, EventArgs e)
{
con = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\\cus1.mdb");
ada = new OleDbDataAdapter("select ubal from cus1 where uname="+this.label3.Text,con);
ds = new DataSet();
//OleDbCommand cmd = new OleDbCommand("SELECT ubal FROM cus1 WHERE uname=#uname");
//ocb = new OleDbCommandBuilder(ada);
//textBox2.Text = label3.Text;
ada.Fill(ds,"cus1");
textBox1.DataBindings.Add("Text", ds, "cus1.ubal");
bm = this.BindingContext[ds.Tables[0]];
// cmd.CommandText ="SELECT treatment FROM appointment WHERE patientid=#patientID";
}
how to solve this?
You are missing single quotes around your text. But to avoid a whole boat load of problems regarding your sql queries, including sql injection, always use parameters:
ada = new OleDbDataAdapter("select ubal from cus1 where uname=?", con);
ada.SelectCommand.Parameters.AddWithValue("?", this.label3.Text);

SQL update command not working

I have created a web page in Asp.net website. The following page load will run as it gets arguments from previous page. The page also has an option for editing the contents and updating in database. But when the button(save) is clicked it doesn't update the database.Kindly help in this. But when there is no connection in page load the update command works.
protected void Page_Load(object sender, EventArgs e)
{
String cust=Request.QueryString["custName"];
String env = Request.QueryString["env"];
SqlConnection cnn = new SqlConnection();
string connStr = ConfigurationManager.ConnectionStrings["cnn"].ConnectionString;
SqlDataAdapter adapter = new SqlDataAdapter();
cnn.ConnectionString = connStr;
cnn.Open();
view();
if (env == "Production")
{
DataSet MyDataSet = new DataSet();
adapter = new SqlDataAdapter("Select * from Customer_Production where Customer_Name=#cust", cnn);
SqlCommandBuilder m_cbCommandBuilder = new SqlCommandBuilder(adapter);
cnn.Close();
//SqlCommand cmd = new SqlCommand("Select * from Customer_Production where Customer_Name=#cust", cnn);
adapter.SelectCommand.Parameters.AddWithValue("#cust", cust);
adapter.Fill(MyDataSet, "Servers");
foreach (DataRow myRow in MyDataSet.Tables[0].Rows)
{
custName.Value = myRow["Customer_name"].ToString();
custMaintain.Value= myRow["Customer_Maintenance"].ToString();
serviceAffect.Value=myRow["Systems/Services_Affected"].ToString();
email_Content.Value= myRow["Email_Content"].ToString();
email_Signature.Value= myRow["Email_Signature"].ToString();
email_From.Value=myRow["Email_From"].ToString();
email_To.Value=myRow["Email_To"].ToString();
email_Cc.Value=myRow["Email_Cc"].ToString();
email_Bcc.Value=myRow["Email_Bcc"].ToString();
}
}
else
{
DataSet MyDataSet = new DataSet();
adapter = new SqlDataAdapter("Select * from Customer_Non_Production where Customer_Name=#cust", cnn);
SqlCommandBuilder m_cbCommandBuilder = new SqlCommandBuilder(adapter);
cnn.Close();
//SqlCommand cmd = new SqlCommand("Select * from Customer_Production where Customer_Name=#cust", cnn);
adapter.SelectCommand.Parameters.AddWithValue("#cust", cust);
adapter.Fill(MyDataSet, "Servers");
foreach (DataRow myRow in MyDataSet.Tables[0].Rows)
{
custName.Value = myRow["Customer_name"].ToString();
custMaintain.Value = myRow["Customer_Maintenance"].ToString();
serviceAffect.Value = myRow["Systems/Services_Affected"].ToString();
email_Content.Value = myRow["Email_Content"].ToString();
email_Signature.Value = myRow["Email_Signature"].ToString();
email_From.Value = myRow["Email_From"].ToString();
email_To.Value = myRow["Email_To"].ToString();
email_Cc.Value = myRow["Email_Cc"].ToString();
email_Bcc.Value = myRow["Email_Bcc"].ToString();
}
}
The following is the button click for Save Button(for update command)
protected void save_click(object sender, EventArgs e)
{
//Button Click Save
/* String id = "A";
SqlConnection cnn = new SqlConnection();
string connStr = ConfigurationManager.ConnectionStrings["cnn"].ConnectionString;
SqlDataAdapter adapter = new SqlDataAdapter();
cnn.ConnectionString = connStr;
cnn.Open();
String sql = String.Format("Update Customer_Production set Email_Signature='{0}' where Customer_Name like '{1}'",TextBox1.Text,id);
SqlCommand cmd = new SqlCommand(sql, cnn);
cmd.ExecuteNonQuery();
*/
String cust = "A";
SqlConnection cnn = new SqlConnection();
string connStr = ConfigurationManager.ConnectionStrings["cnn"].ConnectionString;
SqlDataAdapter adapter = new SqlDataAdapter();
cnn.ConnectionString = connStr;
cnn.Open();
if (env.Value == "Production")
{
//String sql = String.Format("Update Customer_Production set Customer_Maintenance='{0}',Environment='{1}',[Systems/Services_Affected]='{2}',Email_Content='{3}',Email_Signature='{4}',Email_To='{5}',Email_Cc='{6}',Email_Bcc='{7}',Email_From='{8}' where Customer_Name like '{9}' ", "custMaintain.Value","env.Value","serviceAffect.Value","email_Content.Value","email_To.Value","email_Cc.Value","email_Bcc.Value","email_From.Value", "cust");
String sql = String.Format("Update Customer_Production set Email_Signature='{0}' where Customer_Name like '{1}'", email_Signature.Value,cust);
SqlCommand cmd = new SqlCommand(sql, cnn);
cmd.ExecuteNonQuery();
}
else
{
}
}
I'm not sure why having a connection (or not) in the Page_Load would make a difference, but here's one thing that looks off to me:
String.Format(
"Update Customer_Production set Email_Signature='{0}' where Customer_Name like '{1}'",
email_Signature.Value,
cust);
(I broke it into several lines because the part I'm interested in is the last part of the format string.)
You've set cust to "A" earlier in that method. So the SQL that will result will look (at the end) like this:
... where Customer_Name like 'A'
Unless you have a customer name that is exactly equal to A, that's not going to return anything, and therefore no records will be updated. You're forgetting the '%' wildcard.
I agree with all those who have pointed out that your code is vulnerable to SQL injection (and you'll also have a problem with single quotes), but just to show you what it needs to look like, here it is with the wildcard:
Update Customer_Production set Email_Signature='{0}' where Customer_Name like '{1}%'

Categories