I have a simple two-field form that stores its data in the database. For some reason, it isn't working. I have verified that the connection string works, as it is used in another project I made.
I didn't include the beginning of the first class or its page load.
Code:
protected void btnSubmit_Click(object sender, EventArgs e)
{
string Name = txtName.Text;
string Description = txtSpecial.Text;
string method = string.Format(
"INSERT INTO RbSpecials (Name,Description,Active) VALUES ('{0}','{1}','1')",
Name,
Description);
RbConfiguration mySql = new RbConfiguration();
try
{
mySql.Sql_Connection(method);
}
catch
{
}
}
}
public class RbConfiguration
{
string DbConnectionString = "System.Configuration.ConfigurationManager.ConnectionStrings['RBConnectionString'].ConnectionString";
public void Sql_Connection(string queryString)
{
SqlConnection conn = new SqlConnection(DbConnectionString);
SqlCommand cmd = new SqlCommand(queryString, conn);
conn.Open();
conn.Close();
}
}
You never execute your SQL command:
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
And your connection string is wrong (ditch the double quotes):
string DbConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["RBConnectionString"].ConnectionString;
Well without knowing the error, I'll give it a shot anyway.
string DbConnectionString = "System.Configuration.ConfigurationManager.ConnectionStrings['RBConnectionString'].ConnectionString";
Should be
string DbConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["RBConnectionString"].ConnectionString;
And as Adam says, you never actually execute your Query.
The Sql_Connection-method, only opens a connection, and then closes it again, without actually doing anything.
Try this instead:
public void Sql_Connection(string queryString)
{
using( SqlConnection conn = new SqlConnection(DbConnectionString) )
{
SqlCommand cmd = new SqlCommand(queryString, conn);
conn.Open();
cmd.ExecuteNonQuery();
}
}
Check your connection string code must not be a string its class which is getting connection string from web.config, so it should be like this
string DbConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["RBConnectionString"].ConnectionString;
You did not execute your SQlCommand, so will it insert the data, do this
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
its not the cause but the best practice to not to make your code vulnerable to SQLINjection, try this article
How To: Protect From SQL Injection in ASP.NET
Related
Here is my database connection class.I want to access 'oracleCommand' object reference from another class.
public class DBConnection
{
//public OracleCommand oracleCommand;
public string cmd = "";
public void makeConnection()
{
//Opening connection
string connectionString = "XXXX";
OracleConnection con = new OracleConnection();
con.ConnectionString = connectionString;
con.Open();
OracleCommand oracleCommand = con.CreateCommand();
cmd = oracleCommand.CommandText;
//Clossing resources
con.Close();
oracleCommand.Dispose();
}
Then I want to execute the following query.
dbConnection.cmd = "SELECT COUNT(JOB_ID) FROM EmployeeTable WHERE STATUS='Pending'";
OracleDataReader Reader = dbConnection.oracleCommand.ExecuteReader();
Reader.Read();
But 'dbConnection.oracleCommand.ExecuteReader()' does not hit when debugging. Does anyone has an idea?
You´re hiding the member oracleCommand by a variable with the same name that exists within the makeConnection-method. Omit the declaration in your method:
public class DBConnection
{
public OracleCommand oracleCommand;
public string cmd = "";
public void makeConnection()
{
//Opening connection
string connectionString = "XXXX";
OracleConnection con = new OracleConnection();
con.ConnectionString = connectionString;
con.Open();
this.oracleCommand = con.CreateCommand(); // here
cmd = oracleCommand.CommandText;
//Clossing resources
con.Close();
oracleCommand.Dispose();
}
However that won´t help you much as you can´t do anything with the command, because yo dispose it once makeConnection has run.
Furthermore it´s a bad idea to even expose a command to the outside. You should instead expose the connection and create a new command for every statement to be executed on the db:
public class DBConnection
{
public OracleConnection { get; private set; }
public string cmd = "";
public void makeConnection()
{
//Opening connection
string connectionString = "XXXX";
this.Connection = new OracleConnection();
this.Connection.ConnectionString = connectionString;
con.Open();
}
Now create a second method that executes your query and returns its results:
public int CountPendingElements()
{
using(var cmd = this.Connection.CreateCommand())
{
cmd.CommandText = "SELECT COUNT(JOB_ID) FROM EmployeeTable WHERE STATUS='Pending'";
OracleDataReader Reader = cmd.ExecuteReader();
Reader.Read();
return reader.GetInt32(0);
}
}
The using-statement ensures that even in case of an exception within the code-block the command is disposed.
As an aside your class should implement IDisposable to dispose its underlying connection when you´re done with it.
This is the code I'm working with right now, I don't get any errors so I can't pinpoint where it's not working:
private void btnAdd_Click(object sender, EventArgs e)
{
string constring = $"Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=" +
Directory.GetCurrentDirectory().ToString() + "\\BarcodeDB.mdf;Integrated Security=True";
string query =
"INSERT INTO Products (Barcodes, Name, EDate, Quantity, Price) VALUES (#barcodeValue, #nameValue, #dateValue, #quantityValue, #priceValue) ;";
SqlConnection conDataBase = new SqlConnection(constring);
conDataBase.Open();
using (var cmd = new SqlCommand(query, conDataBase))
{
cmd.Parameters.AddWithValue("#barcodeValue", tbxBar.Text);
cmd.Parameters.AddWithValue("#nameValue", tbxName.Text);
cmd.Parameters.AddWithValue("#dateValue", dateDate.Value.Date);
cmd.Parameters.AddWithValue("#quantityeValue", tbxQua.Text);
cmd.Parameters.AddWithValue("#priceValue", tbxPrice.Text);
}
conDataBase.Close();
}
The code might just be wrongly build or I could be missing some part I'm not sure.
I figured out what was not working, was the connection string. So opening a new question for that.
What i had to do is to open the connection and then execute the command
You're not actually running the command. You need to call ExecuteNonQuery or ExecuteScalar:
using (var cmd = new SqlCommand(query, conDataBase))
{
// set parameters...
cmd.ExecuteNonQuery();
}
Changes are not saved to the SQL database
Why would I want to use '#' in the sql statement instead of the way that I have the statement?
Code:
private void button_Save_Customer_Click(object sender, EventArgs e)
{
sqlString = Properties.Settings.Default.ConnectionString;
SqlConnection sqlConnection = new SqlConnection(sqlString);
try
{
string customer_Ship_ID = customer_Ship_IDTextBox.ToString();
string customer_Ship_Address = customer_Ship_AddressTextBox.Text;
SQL = "UPDATE Customer_Ship SET Customer_Ship_Address = customer_Ship_Address WHERE Customer_Ship_ID = customer_Ship_ID";
SqlCommand sqlCommand = new SqlCommand(SQL, sqlConnection);
sqlCommand.Parameters.AddWithValue("Customer_Ship_ID", customer_Ship_ID);
sqlCommand.Parameters.AddWithValue("Customer_Ship_Address", customer_Ship_Address);
sqlCommand.CommandText = SQL;
sqlConnection.Open();
sqlCommand.ExecuteNonQuery();
sqlConnection.Close();
MessageBox.Show("Record Updated");
}
catch (Exception err)
{
MessageBox.Show(err.Message);
}
Here you can check the MSDN reference for the update command.
Use parameters, Why?
Also check that you need to open and close the connection object, not the command.
In case you want to update the rows with the Customer_ID = "something" you could do like this:
The code (updated after your changes):
private void button_Save_Customer_Click(object sender, EventArgs e)
{
string sqlString = Properties.Settings.Default.ConnectionString;
SqlConnection sqlConnection = new SqlConnection(sqlString);
try
{
int customer_Ship_ID;
if(int.TryParse(customer_Ship_IDTextBox.Text, out customer_Ship_ID))
{
string customer_Ship_Address = customer_Ship_AddressTextBox.Text;
// Customer_Ship: Database's table
// Customer_Ship_Address, Customer_Ship_ID: fields of your table in database
// #Customer_Ship_Address, #Customer_Ship_ID: parameters of the sqlcommand
// customer_Ship_ID, customer_Ship_Address: values of the parameters
string SQL = "UPDATE Customer_Ship SET Customer_Ship_Address = #Customer_Ship_Address WHERE Customer_Ship_ID = #Customer_Ship_ID";
SqlCommand sqlCommand = new SqlCommand(SQL, sqlConnection);
sqlCommand.Parameters.AddWithValue("Customer_Ship_ID", customer_Ship_ID);
sqlCommand.Parameters.AddWithValue("Customer_Ship_Address", customer_Ship_Address);
sqlCommand.CommandText = SQL;
sqlConnection.Open();
sqlCommand.ExecuteNonQuery();
sqlConnection.Close();
MessageBox.Show("Record Updated");
}
else
{
// The id of the textbox is not an integer...
}
}
catch (Exception err)
{
MessageBox.Show(err.Message);
}
}
Seems like your syntax isn't correct. Here's the syntax for the Update:
UPDATE table_name
SET column1=value1,column2=value2,...
WHERE some_column=some_value;
So, Update, what to set, and WHERE to set (which you seem to be missing).
For more, have a look here.
Check your update query
Change it like
string SQL = string.format("UPDATE Customer_Ship SET Customer_Ship_Address='{0}'",putUrVaue);
i have been trying to insert data to my database with ASP.net
the code with which i have been trying to insert data:
protected void btnInsert_Click(object sender, EventArgs e)
{
// connection
SqlConnection connection = new SqlConnection();
connection.ConnectionString = #"Data Source=YANNICK\SQLEXPRESS; Initial Catalog=Klas; Integrated Security=True";
SqlCommand command = new SqlCommand();
command.Connection = connection;
// values de insert statement toewijzen
command.Parameters.AddWithValue("#kijkerv", txtGastV.Text);
command.Parameters.AddWithValue("#kijkerT_V", txtGastT_V.Text);
command.Parameters.AddWithValue("#KijkerA", txtGastA.Text);
command.Parameters.AddWithValue("#KijkerEmail", txtEmail.Text);
command.Parameters.AddWithValue("#Kijkershow", txtShowId.integer;
// insert statement
command.CommandText = "INSERT INTO tblKijker (Kijkerv, KijkerT_V, KijkerA, ShowId, Email) VALUES (#kijkerv,
#kijkerT_V, #KijerA, #KijkerEmail, #Kijkershow);";
try {
connection.open();
int rowsAffected = command.ExecuteNonQuery();
} catch (Exception ex) {
// handle exception
} finally {
connection.close();
}
}
the error message is: newline in constant
what does this error mean/ how to fix it?
Your query string CommandText is in two lines. Remove the newline or put # before your query string like this :
command.CommandText = #"INSERT INTO tblKijker (Kijkerv, KijkerT_V, KijkerA, ShowId, Email) VALUES (#kijkerv,
#kijkerT_V, #KijerA, #KijkerEmail, #Kijkershow);"
i have found my own problem:
i had forgotten to add the libraries to set up a connction to my sql into my file
the code would look like this:
// library to work in DATABASES
using System.Data;
// library especially for SQL
using System.Data.SqlClient;
Below are my codes, I have tried the ToString() but it will prompt out error upon running the codes. I want to use the "newName" as my condition to display out what I needed. Any help would be appreciated.
void onFoodLoad() {
SqlConnection conn = new SqlConnection(dbConn);
SqlCommand cmd;
String connStr;
string newName = name.Content.ToString();
try {
conn.Open();
//problem here
connStr = "Select Ingredients, Directions From Food where FoodName = #newFoodName";
cmd = new SqlCommand(connStr, conn);
cmd.Parameters.AddWithValue("#nnewFoodName", SqlDbType.NVarChar);
cmd.Parameters["#newFoodName"].Value = newName;
SqlDataReader reader = cmd.ExecuteReader();
if (reader.Read())
{
//name.Content = reader["FoodName"];
ingredient.Content = reader["Ingredients"];
direction.Content = "Directions "+ reader["Directions"];
}
conn.Close();
}
catch(Exception ex){
MessageBox.Show(ex.Message);
}
}
Change connStr to something like:
connStr = "Select Ingredients, Directions From Food where FoodName = #NewFoodName";
And add:
cmd.Parameters.AddWithValue("#NewFoodName", newName);
after creating the SqlCommand.
Kind of a side thing, but you should definitely wrap your Sql* creation in a using block so that it gets properly disposed after you're done with it, unless of course you are properly disposing of it yourself.