C# SQL Server database update data - c#

I want to update data in a SQL Server database but something is wrong. My code does not update the database and I don't know what the problem is
if (d.Contains("1"))
{
sql1 = "UPDATE Faucets SET Enabled='0' WHERE FaucetName='" + dataGridView1.Rows[e.RowIndex].Cells[1].Value + "'";
}
else
{
sql1 = "UPDATE Faucets SET Enabled='1' WHERE FaucetName='" + dataGridView1.Rows[e.RowIndex].Cells[1].Value + "'";
}
SqlConnection connect1 = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\faucets.mdf;Integrated Security=True");
connect1.Open();
SqlCommand parancs1 = connect1.CreateCommand();
parancs1.CommandType = CommandType.Text;
parancs1.CommandText = sql1;
parancs1.ExecuteNonQuery();
connect1.Close();

Related

creating connection string for attached MDF file

what you see bellow is a part of my WPF project I used it to backup/restore my SQL server database and it works great but; when I want to make a setup file by advanced installer and I move MDF and LDF files created by SQL script to app directory to use in SQL express it doesn't work. Now I want to know what can I do with connection string so that backup/restore prosses can work correctly
private string connectionString = "Data Source=.\\SQLEXPRESS;AttachDbFileName=|DataDirectory|\\DBNBO.mdf;Database=DBNBO; Trusted_Connection=Yes;";
private void BtnBackup_OnClick(object sender, EventArgs e)
{
SqlConnection connection = new SqlConnection(connectionString);
string database = connection.Database;
string query = "Backup Database [" + database + "] To Disk = '" + txtBackup.Text + "\\DB_backup.bak'";
SqlCommand command = new SqlCommand(query, connection);
connection.Open();
command.ExecuteNonQuery();
connection.Close();
}
private void btnRestore_Click(object sender, EventArgs e)
{
SqlConnection connection = new SqlConnection(connectionString);
string database = connection.Database;
if (connection.State != ConnectionState.Open) connection.Open();
string query1 = string.Format("Alter Database [" + database + "] Set Single_User With Rollback Immediate");
SqlCommand command1 = new SqlCommand(query1, connection);
command1.ExecuteNonQuery();
string query2 = string.Format("Use Master Restore Database [" + database + "] From Disk = '" + txtRestore.Text + "' With Replace");
SqlCommand command2 = new SqlCommand(query2, connection);
command2.ExecuteNonQuery();
string query3 = string.Format("Alter Database [" + database + "] Set Multi_User");
SqlCommand command3 = new SqlCommand(query3, connection);
command3.ExecuteNonQuery();
connection.Close();
}

Insert command works without errors in C# but data is not inserted to the MS SQL Server

I am trying to insert data into Microsoft SQL Server DB using C# and the insert command works well and I get no errors or exceptions. But when I check my database in SQL Server there is no effect on the table and the records are not inserted into the table. This is the code that I try:
try
{
SqlConnection con1 = new SqlConnection();
con1.ConnectionString = "Server = (local); Database = My_DataBase; Integrated Security = true";
con1.Open();
SqlCommand cm1 = new SqlCommand();
cm1.Connection = con1;
cm1.CommandText = "insert into Users values('" + update.Message.Chat.Id.ToString() + "','" + update.Message.Chat.FirstName + "','" + update.Message.Chat.LastName + "','#" + update.Message.Chat.Username + "','" + req1.Status + "')";
con1.Close();
}
catch(Exception e)
{
Console.WriteLine(e.Message);
continue;
}
I've seen similar questions here and here, but the answers did not fix my problem.
Also when I insert data to the DB manually and run select command like mentioned below, I get the correct answer but for the insert command I do not.
SqlConnection con2 = new SqlConnection();
con2.ConnectionString = "Server = (local); Database = My_DataBase; Integrated Security = true";
con2.Open();
SqlDataAdapter da1 = new SqlDataAdapter("select * from Users where ChatID='" + update.Message.Chat.Id.ToString() + "'", con2);
DataSet ds1 = new DataSet();
da1.Fill(ds1);
con1.Close();
Please help me fix this issue.
By the way I know that this kind of insertion is not safe and I'l like to let you know that this is just a demo and I will make it secure against sql injection.
You are not executing your command anywhere.
You need:
cm1.ExecuteNonQuery();
In your code, you are creating a SqlCommand object, then you associate a SqlConnection to it, but in no where you are actually executing the command. Your code should look like:
SqlConnection con1 = new SqlConnection();
con1.ConnectionString = "Server = (local); Database = My_DataBase; Integrated Security = true";
con1.Open();
SqlCommand cm1 = new SqlCommand();
cm1.Connection = con1;
cm1.CommandText = "insert into Users values('" + update.Message.Chat.Id.ToString() + "','" + update.Message.Chat.FirstName + "','" + update.Message.Chat.LastName + "','#" + update.Message.Chat.Username + "','" + req1.Status + "'";
cm1.ExecuteNonQuery();
con1.Close();
Apart from SQL Injection vulnerability, you should consider enclosing your SqlCommand and SqlConnection object in using statement, that will ensure proper disposal of un-managed resources.

More efficient way of running multiple update queries on an Access database?

I have multiple queries like this right now which involve updating different fields of the same row in an Access database:
//Update database
string updatequery = "UPDATE [table] SET [Last10Attempts] = ? WHERE id = ?";
OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;" + #"Data Source=" + "database.accdb");
con.Open();
OleDbDataAdapter da = new OleDbDataAdapter(updatequery, con);
var accessUpdateCommand = new OleDbCommand(updatequery, con);
accessUpdateCommand.Parameters.AddWithValue("Last10Attempts", last10attempts);
accessUpdateCommand.Parameters.AddWithValue("ID", currentid + 1);
da.UpdateCommand = accessUpdateCommand;
da.UpdateCommand.ExecuteNonQuery();
//update last10attemptssum
updatequery = "UPDATE [table] SET [Last10AttemptsSum] = ? WHERE id = ?";
accessUpdateCommand = new OleDbCommand(updatequery, con);
accessUpdateCommand.Parameters.AddWithValue("Last10AttemptsSum", counter);
accessUpdateCommand.Parameters.AddWithValue("ID", currentid + 1);
da.UpdateCommand = accessUpdateCommand;
da.UpdateCommand.ExecuteNonQuery();
//increment totalquestionattempt
updatequery = "UPDATE [table] SET [total-question-attempts] = ? WHERE id = ?";
accessUpdateCommand = new OleDbCommand(updatequery, con);
accessUpdateCommand.Parameters.AddWithValue("total-question-attempts", questionattempts + 1);
accessUpdateCommand.Parameters.AddWithValue("ID", currentid + 1);
da.UpdateCommand = accessUpdateCommand;
da.UpdateCommand.ExecuteNonQuery();
con.Close();
I was wondering if there is a more efficient way of running these update queries - ie. combining them into one query.
There is no need to use an OleDbDataAdapter in your context above. You could use a simple command and execute it
Said that, an Update sql statement can update more than one field. Just write
string updatequery = #"UPDATE [table] SET [Last10Attempts] = ?,
[Last10AttemptsSum] = ?,
[total-question-attempts] = ?
WHERE id = ?";
using(OleDbConnection con = new OleDbConnection(.........))
using(OleDbCommand cmd = new OleDbCommand(updatequery, con))
{
con.Open();
cmd.Parameters.AddWithValue("Last10Attempts", last10attempts);
cmd.Parameters.AddWithValue("Last10AttemptsSum", counter);
cmd.Parameters.AddWithValue("total-question-attempts", questionattempts + 1);
cmd.Parameters.AddWithValue("ID", currentid + 1);
cmd.ExecuteNonQuery();
}
The only thing to keep present when working with OleDb is the fact that the parameters are used in the exact order in which the parameter placeholder appears in the command text. So they should be added to the parameter collection in the order expected by the command text

How to run multiple SQL commands in a single SQL connection?

I am creating a project in which I need to run 2-3 SQL commands in a single SQL connection.
Here is the code I have written:
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\project.mdf;Integrated Security=True");
con.Open();
SqlCommand cmd = new SqlCommand("select * from " + mytags.Text + " ", con);
SqlDataReader rd = cmd.ExecuteReader();
if (rd.Read())
{
con.Close();
con.Open();
SqlCommand cmd1 = new SqlCommand("insert into " + mytags.Text + " values ('fname.lname#gmail.com','" + TextBox3.Text + "','" + TextBox4.Text + "','" + TextBox5.Text + "','"+mytags.Text+"')", con);
cmd1.ExecuteNonQuery();
label.Visible = true;
label.Text = "Date read and inserted";
}
else
{
con.Close();
con.Open();
SqlCommand cmd2 = new SqlCommand("create table " + mytags.Text + " ( session VARCHAR(MAX) , Price int , Description VARCHAR(MAX), Date VARCHAR(20),tag VARCHAR(10))", con);
cmd2.ExecuteNonQuery();
con.Close();
con.Open();
SqlCommand cmd3 = new SqlCommand("insert into " + mytags.Text + " values ('" + Session + "','" + TextBox3.Text + "','" + TextBox4.Text + "','" + TextBox5.Text + "','" + mytags.Text + "')", con);
cmd3.ExecuteNonQuery();
label.Visible = true;
label.Text = "tabel created";
con.Close();
}
I have tried to remove the error and I got that the connection is not going to else condition. Please review the code and suggest if there is any mistake or any other solution for this.
Just change the SqlCommand.CommandText instead of creating a new SqlCommand every time. There is no need to close and reopen the connection.
// Create the first command and execute
var command = new SqlCommand("<SQL Command>", myConnection);
var reader = command.ExecuteReader();
// Change the SQL Command and execute
command.CommandText = "<New SQL Command>";
command.ExecuteNonQuery();
The following should work. Keep single connection open all time, and just create new commands and execute them.
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
using (SqlCommand command1 = new SqlCommand(commandText1, connection))
{
}
using (SqlCommand command2 = new SqlCommand(commandText2, connection))
{
}
// etc
}
Just enable this property in your connection string:
sqb.MultipleActiveResultSets = true;
This property allows one open connection for multiple datareaders.
I have not tested , but what the main idea is: put semicolon on each query.
SqlConnection connection = new SqlConnection();
SqlCommand command = new SqlCommand();
connection.ConnectionString = connectionString; // put your connection string
command.CommandText = #"
update table
set somecol = somevalue;
insert into someTable values(1,'test');";
command.CommandType = CommandType.Text;
command.Connection = connection;
try
{
connection.Open();
}
finally
{
command.Dispose();
connection.Dispose();
}
Update:
you can follow
Is it possible to have multiple SQL instructions in a ADO.NET Command.CommandText property? too
This is likely to be attacked via SQL injection by the way. It'd be worth while reading up on that and adjusting your queries accordingly.
Maybe look at even creating a stored proc for this and using something like sp_executesql which can provide some protection against this when dynamic sql is a requirement (ie. unknown table names etc). For more info, check out this link.
No one has mentioned this, but you can also separate your commands using a ; semicolon in the same CommandText:
using (SqlConnection conn = new SqlConnection(connString))
{
using (SqlCommand comm = new SqlCommand())
{
comm.Connection = conn;
comm.CommandText = #"update table ... where myparam=#myparam1 ; " +
"update table ... where myparam=#myparam2 ";
comm.Parameters.AddWithValue("#myparam1", myparam1);
comm.Parameters.AddWithValue("#myparam2", myparam2);
conn.Open();
comm.ExecuteNonQuery();
}
}
Multiple Non-query example if anyone is interested.
using (OdbcConnection DbConnection = new OdbcConnection("ConnectionString"))
{
DbConnection.Open();
using (OdbcCommand DbCommand = DbConnection.CreateCommand())
{
DbCommand.CommandText = "INSERT...";
DbCommand.Parameters.Add("#Name", OdbcType.Text, 20).Value = "name";
DbCommand.ExecuteNonQuery();
DbCommand.Parameters.Clear();
DbCommand.Parameters.Add("#Name", OdbcType.Text, 20).Value = "name2";
DbCommand.ExecuteNonQuery();
}
}
Here you can find Postgre example, this code run multiple sql commands (update 2 columns) within single SQL connection
public static class SQLTest
{
public static void NpgsqlCommand()
{
using (NpgsqlConnection connection = new NpgsqlConnection("Server = ; Port = ; User Id = ; " + "Password = ; Database = ;"))
{
NpgsqlCommand command1 = new NpgsqlCommand("update xy set xw = 'a' WHERE aa='bb'", connection);
NpgsqlCommand command2 = new NpgsqlCommand("update xy set xw = 'b' where bb = 'cc'", connection);
command1.Connection.Open();
command1.ExecuteNonQuery();
command2.ExecuteNonQuery();
command2.Connection.Close();
}
}
}
using (var connection = new SqlConnection("Enter Your Connection String"))
{
connection.Open();
using (var command = connection.CreateCommand())
{
command.CommandText = "Enter the First Command Here";
command.ExecuteNonQuery();
command.CommandText = "Enter Second Comand Here";
command.ExecuteNonQuery();
//Similarly You can Add Multiple
}
}
It worked for me.

MySQL Password Login Code?

I'm trying to do a Login code in C# with MySQL. Basically the user enters a username and password then the code checks the database if the the password is correct. I'm having trouble getting the code to read from the data base... Here is where I'm at.
public string strUsername;
public string strPassword;
//Connect to DataBase
MySQLServer.Open();
//Check Login
MySqlDataReader mySQLReader = null;
MySqlCommand mySQLCommand = MySQLServer.CreateCommand();
mySQLCommand.CommandText = ("SELECT * FROM user_accounts WHERE username =" +strUsername);
mySQLReader = mySQLCommand.ExecuteReader();
while (mySQLReader.Read())
{
string TruePass = mySQLReader.GetString(1);
if (strPassword == TruePass)
{
blnCorrect = true;
//Get Player Data
}
}
MySQLServer.Close();
From what I've done in the past, I thought this would work but if I print it, it Seems like its not being read. I am still fairly new to MySQL so any help would be Great.
Non-numeric field value must be enclosed with single quote.
mySQLCommand.CommandText = "SELECT * FROM user_accounts WHERE username ='" +strUsername + "'";
mySQLCommand.Connection=MySQLServer;
but you have to use Parameters to prevent SQL Injection.
mySQLCommand.CommandText = "SELECT * FROM user_accounts WHERE username =#username";
mySQLCommand.Connection=MySQLServer;
mySQLCommand.Parameters.AddWithValue("#username",strUsername);
string con_string = #"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Database.mdf;Integrated Security=True;User Instance=True";
string query = "SELECT * FROM Users WHERE UseName='" + txtUserName.Text.ToString() + "' AND Password='" + txtPassword.Text + "'";
SqlConnection Con = new SqlConnection(con_string);
SqlCommand Com = new SqlCommand(query, Con);
Con.Open();
SqlDataReader Reader;
Reader = Com.ExecuteReader();
if (Reader.Read())
{
lblStatus.Text="Successfully Login";
}
else
{
lblStatus.Text="UserName or Password error";
}
Con.Close();
As AVD said you should use parameters to prevent sql injection....

Categories