I want to insert document number into adjustments_config table in the vm server like this:
public string conString = "Data Source=vmrserver;Initial Catalog=Commission_web;Integrated Security=True";
SqlConnection con = new SqlConnection(conString);
con.Open();
if(con.State == System.Data.ConnectionState.Open)
{
string q = "insert into adjustments_config(document_number)values('" + TextBoxDocNo.Text + "')";
SqlCommand cmd = new SqlCommand(q, con);
cmd.ExecuteNonQuery();
Response.Redirect("About.aspx");
}
I can't possibly tell what you problem is without more information but your SQL is vulnerable to SQL injection. Perhaps the problem with your code is that your document number has an apostrophe in it, causing your vulnerable code to blow up.
Try this to get you started:
try
{
using(var con = new SqlConnection(conString))
using(var cmd = new SqlCommand("insert into adjustments_config(document_number)values(#docNumber)", con)
{
con.Open();
cmd.Parameters.AddWithValue("#docNumber", TextBoxDocNo.Text);
var rowsAffected = cmd.ExecuteNonQuery();
// ..validate rows affected
Response.Redirect("About.aspx");
}
}
catch(SqlException ex)
{
MessageBox.Show(ex.Message);
}
Related
IWhat i wanna do
So I tried this code
but it coudnt get a connection with the Database. I the connection string is correct
SqlConnection con = new SqlConnection("server=localhost;uid=root;database=menucreator");
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "insert into [kunde]Vorname()values(#nm)";
cmd.Parameters.AddWithValue("#nm", Vorname.Text);
cmd.Connection = con;
SqlCommand cmdd = new SqlCommand();
cmdd.CommandText = "insert into [kunde]Nachname()values(#nmm)";
cmdd.Parameters.AddWithValue("#nmm", Nachname.Text);
cmdd.Connection = con;
int a = cmd.ExecuteNonQuery();
if (a == 1)
{
MessageBox.Show("Dateien bitte");
}
follow the following code. It inserts two columns into a table (tableName). Maintain proper space in SQL query as showing in below sample code. ALso, it's best practice to keep the code in a try-catch block to capture any error that occurs during DB operation.
try
{
SqlConnection con = new SqlConnection("server=localhost;uid=root;database=menucreator");
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "insert into tableName(column1,column2) values(#nm,#nmm)";
cmd.Parameters.AddWithValue("#nm", Vorname.Text);
cmd.Parameters.AddWithValue("#nmm", Nachname.Text);
cmd.Connection = con;
int a = cmd.ExecuteNonQuery();
if (a == 1)
{
MessageBox.Show("Dateien bitte");
}
}
catch (Exception ex)
{
MessageBox.Show("Error:"+ex.ToString());
}
The code compiles fine without error or warning, but the database does not change. I mean the changes are not saved to the database.
I wrote the following methods:
private void Test2()
{
connection = new SqlConnection();
string Conn = #"Data Source=(LocalDB)\MSSQLLocalDB;"
+ #"AttachDbFilename=|DataDirectory|\User.mdf;"
+ "Integrated Security=True;"
+ "Connect Timeout=30";
// string sqlString = Properties.Settings.Default.ConnectionString;
SqlConnection sqlConnection = new SqlConnection(Conn);
try
{
string SQL = "UPDATE Primuser SET Following = #Following WHERE Insta = #Insta";
SqlCommand sqlCommand = new SqlCommand(SQL, sqlConnection);
sqlCommand.Parameters.AddWithValue("#Following", "123");
sqlCommand.Parameters.AddWithValue("#Insta", "hgd");
sqlCommand.CommandText = SQL;
sqlConnection.Open();
sqlCommand.ExecuteNonQuery();
sqlConnection.Close();
MessageBox.Show("Record Updated");
}
catch (Exception err)
{
MessageBox.Show(err.Message);
}
}
and in this Code, the result is bigger than 0.
private void Test2()
{
connection = new SqlConnection();
connection.ConnectionString = #"Data Source=(LocalDB)\MSSQLLocalDB;"
+ #"AttachDbFilename=|DataDirectory|\User.mdf;"
+ "Integrated Security=True;"
+ "Connect Timeout=30";
SqlCommand command = new SqlCommand();
command.CommandText = "SELECT * FROM Primuser";
command.Connection = connection;
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = command;
DataSet dataset = new DataSet();
adapter.Fill(dataset, "Primuser");
foreach (DataRow row in dataset.Tables["Primuser"].Rows)
{
if (row["Insta"].ToString() == "1495")
{
row["Following"] = "1024";
}
}
SqlCommandBuilder builder = new SqlCommandBuilder(adapter);
try
{
var result = adapter.Update(dataset, "Primuser");
if (result > 0)
MessageBox.Show("Update Successful.");
else
MessageBox.Show("Update Failed.");
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
}
but the database does not get changed. There are no errors and other query is working. I can insert, delete or select, but update is not working.
Well, I work little bit with C # and I'm starting to work with Database with C # now, I've googled in several places and I am unable to identify where it is wrong, everywhere say I need to open a connection, but it is already open .
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0;Integrated Security=True;AttachDbFilename=C:\Users\Gustavo\Documents\Visual Studio 2013\Projects\hour\hour\Database1.mdf");
con.Open();
try
{
string query = "INSERT INTO [Table] (name, time) VALUES ('test',1)";
SqlCommand cmd = new SqlCommand(query);
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
Use using, takes care of the closing and disposal for you just in case you forget to do it explicitly. Put it inside the try, you have the connection open command outside the try so it wont catch any connection error. You probably want to look at parameterizing your command too.
using (SqlConnection conn = new SqlConnection(#"Data Source=(LocalDB)\v11.0;Integrated Security=True;AttachDbFilename=C:\Users\Gustavo\Documents\Visual Studio 2013\Projects\hour\hour\Database1.mdf"))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand("INSERT INTO [Table] (name, time) VALUES (#name,#time)", conn))
{
cmd.Parameters.AddWithValue("#name", "test");
cmd.Parameters.AddWithValue("#time", 1);
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
}
}
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0;Integrated Security=True;AttachDbFilename=C:\Users\Gustavo\Documents\Visual Studio 2013\Projects\hour\hour\Database1.mdf");
try
{
string query = "INSERT INTO [Table] (name, time) VALUES ('test',1)";
SqlCommand cmd = new SqlCommand(query,con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
you need to assign the command to the connection. eg:
private static void ReadOrderData(string connectionString)
{
string queryString =
"SELECT OrderID, CustomerID FROM dbo.Orders;";
using (SqlConnection connection = new SqlConnection(
connectionString))
{
//----
SqlCommand command = new SqlCommand(
queryString, connection);
//----
connection.Open();
SqlDataReader reader = command.ExecuteReader();
try
{
while (reader.Read())
{
Console.WriteLine(String.Format("{0}, {1}",
reader[0], reader[1]));
}
}
finally
{
// Always call Close when done reading.
reader.Close();
}
}
}
I have written some C# to update a MySql table but I get an exception every time I call the method ExecuteNonQuery(). I have researched this on the web and every solution I find produces the same error. I have an open connection to the database and the update query to the database is written correctly. The code that I have so far come up with is :
public int executeUpdate()
{
int result = 0;
if (isConnected)
{
try
{
MySqlConnection cn = new MySqlConnection(connection.ConnectionString);
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = cn;
cmd.CommandText = "UPDATE test SET status_id = 1 WHERE test_id = 1";
int numRowsUpdated = cmd.ExecuteNonQuery();
}
catch (MySqlException exSql)
{
Console.Error.WriteLine("Error - SafeMySql: SQL Exception: " + query);
Console.Error.WriteLine(exSql.StackTrace);
}
catch (Exception ex)
{
Console.Error.WriteLine("Error - SafeMySql: Exception: " + query);
Console.Error.WriteLine(ex.StackTrace);
}
}
else
Console.Error.WriteLine("Error - SafeMySql: executeQuery failed. Not connected to DB");
}
Change your try section to the code below:
try
{
using(MySqlConnection cn = new MySqlConnection(connection.ConnectionString))
{
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = cn;
cmd.CommandText = "UPDATE test SET status_id = 1 WHERE test_id = 1";
cn.Open();
int numRowsUpdated = cmd.ExecuteNonQuery();
cmd.Dispose();
}
}
The connection must be opened before you execute a command. In the example above the command object will immediately be disposed and the connection object will implcitly be closed and disposed when you leave the using section.
I don't see the connection being opened.
Here is an example from MSDN: even inside a using block, they open the connection explicitly
private static void CreateCommand(string queryString,
string connectionString)
{
using (SqlConnection connection = new SqlConnection(
connectionString))
{
SqlCommand command = new SqlCommand(queryString, connection);
command.Connection.Open();
command.ExecuteNonQuery();
}
}
Edit: The principle is the same for MySQL as it is for SQL Server:
public void CreateMySqlCommand(string myExecuteQuery, MySqlConnection myConnection)
{
MySqlCommand myCommand = new MySqlCommand(myExecuteQuery, myConnection);
myCommand.Connection.Open();
myCommand.ExecuteNonQuery();
myConnection.Close();
}
I am new to C#.
Kindly tell me what`s wrong with this code. I am inserting data in data base using two input fields EndValueTextBox and StartValueTextBox .
I am receiving following error. "Object reference not set to an instance of an object"
private void buttonSave_Click(object sender, EventArgs e)
{
connection = new System.Data.SqlClient.SqlConnection();
da = new SqlDataAdapter();
try
{
connection.ConnectionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename='G:\\C#.Net\\Forms Practice\\WindowsFormsPractice1\\WindowsFormsPractice1\\WindowsFormsPractice1.mdf';Integrated Security=True;Connect Timeout=30;User Instance=True";
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message,"Connection String");
}
try
{
connection.Open();
string sql = "insert into TBLWORKERS (first_name , last_name )" + " values('" + StartValueTextBox.Text + "', '" + EndValueTextBox.Text + ")";
//SqlDataAdapter da = new SqlDataAdapter(query, connString);
da.InsertCommand.CommandText = sql;
da.InsertCommand.ExecuteNonQuery();
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message, "Connection open");
}
}
Your SqlDataAdapter is never assigned a connection to execute the query on. You need to associate the SqlConnection with the SqlDataAdapter during or after construction.
This line da.InsertCommand.CommandText = sql; has to be in that way:
da.InsertCommand = new SqlCommand(sql);
At what point you are the exception? Probably those line
System.Data.SqlClient.SqlConnection connection = new System.Data.SqlClient.SqlConnection();
SqlDataAdapter da = new SqlDataAdapter();
string connetionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename='G:\\C#.Net\\Forms Practice\\WindowsFormsPractice1\\WindowsFormsPractice1\\WindowsFormsPractice1.mdf';Integrated Security=True;Connect Timeout=30;User Instance=True";
SqlDataAdapter adapter = new SqlDataAdapter();
string sql = "insert into TBLWORKERS (first_name , last_name )" + " values('" + StartValueTextBox.Text + "', '" + EndValueTextBox.Text + ")";
SqlConnection connection = new SqlConnection(connetionString);
try {
connection.Open();
adapter.InsertCommand = new SqlCommand(sql, connection);
adapter.InsertCommand.ExecuteNonQuery();
} catch (Exception ex) {
MessageBox.Show(ex.Message);
}
Here's a minor rewrite of your code (not tested) that should take care of the SqlDataAdapter not having the connection object assigned and also demonstrates how to use parameterized queries to help defend against SQL Injection attacks:
private void buttonSave_Click(object sender, EventArgs e)
{
try
{
// The using block will automatically dispose of your connection when
// the block is exited and is considered standard practice.
using (SqlConnection connection = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename='G:\\C#.Net\\Forms Practice\\WindowsFormsPractice1\\WindowsFormsPractice1\\WindowsFormsPractice1.mdf';Integrated Security=True;Connect Timeout=30;User Instance=True";))
{
SqlDataAdpter da = new SqlDataAdapter();
connection.Open();
// Assign the SqlConnection object to the SqlDataAdapter
da.Connection = connection;
// Parameterize the query as shown below
string sql = "INSERT INTO TBLWORKERS(first_name, last_name) VALUES(#first_name, #last_name)";
da.InsertCommand.CommandText = sql;
// Add the values for the parameters
da.InsertCommand.Parameters.Add("#first_name", SqlDbType.NVarChar, 25, StartValueTextBox.Text);
da.InsertCommand.Parameters.Add("#last_name", SqlDbType.NVarChar, 25, EndValueTextBox.Text);
// Execute the query - rows will have the number of rows
// affected. should be 1 in this case if succesful
int rows = da.InsertCommand.ExecuteNonQuery();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Connection open");
}
}