Update SQL table using C# - c#

I'm trying to update EpisodeId no:117 in the Episode table and it executes successfully but when I check the table it is not updated. int episode Id = 117;
int seriesNumber = 9;
int episodeNumber = 13;
string episodeType = "abnormal episode";
string title = "Reconsideration";
string notes = "recuring behaviour";
//connectionString
string connectionString = "data source=LAPTOP-VLO4EFFQ\\MSSQLSERVER01; database=DoctorWho; integrated Security=True;";
//connection using
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
Console.WriteLine("Connection sucessfull");
string query = "UPDATE tblEpisode " +
"(SeriesNumber, EpisodeNumber, EpisodeType, Title, Notes)" +
"(SET SeriesNumber=#SeriesNumber, EpisodeNumber=#EpisodeNumber, EpisodeType=#EpisodeType, Title=#Title, Notes=#Notes)" +
"(WHERE EpisodeId=#EpisodeId)";
using (SqlCommand command = new SqlCommand(query, conn))
{
//updating data in the sql table with the initial variables
command.Parameters.Add("#EpisodeId", System.Data.SqlDbType.Int).Value = episodeId;
command.Parameters.Add("#SeriesNumber", System.Data.SqlDbType.Int).Value = seriesNumber;
command.Parameters.Add("#EpisodeNumber", System.Data.SqlDbType.Int).Value = episodeNumber;
command.Parameters.Add("#EpisodeType", System.Data.SqlDbType.NVarChar).Value = episodeType;
command.Parameters.Add("#Title", System.Data.SqlDbType.NVarChar).Value = title;
command.Parameters.Add("#Notes", System.Data.SqlDbType.NVarChar).Value = notes;
}
conn.Close();
Console.WriteLine("connection is closed!!");
}

There are some issues with your SQL update statement.Look at following for reference to Update Statement in SQL LINK
There is also an easier way to add the parameters using the AddWithValue Method. LINK
Next, you are not executing the SQL command. For Update statements use the ExecuteNonQuery() method. LINK
Also as #Nikki9696 mentioned, episodeId is not declared. Make sure to declare episodeId with your other variables.
int episodeId = 117;
int seriesNumber = 9;
int episodeNumber = 13;
string episodeType = "abnormal episode";
string title = "Reconsideration";
string notes = "recuring behaviour";
//connectionString
string connectionString = "data source=LAPTOP-VLO4EFFQ\\MSSQLSERVER01; database=DoctorWho; integrated Security=True;";
//connection using
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
Console.WriteLine("Connection sucessfull");
string query = "UPDATE tblEpisode " +
"SET SeriesNumber=#SeriesNumber, EpisodeNumber=#EpisodeNumber, EpisodeType=#EpisodeType, Title=#Title, Notes=#Notes " +
" WHERE EpisodeId=#EpisodeId;";
using (SqlCommand command = new SqlCommand(query, conn))
{
//updating data in the sql table with the initial variables
command.Parameters.AddWithValue("#EpisodeId", episodeId);
command.Parameters.AddWithValue("#SeriesNumber", seriesNumber);
command.Parameters.AddWithValue("#EpisodeNumber", episodeNumber);
command.Parameters.AddWithValue("#EpisodeType", episodeType);
command.Parameters.AddWithValue("#Title", title);
command.Parameters.AddWithValue("#Notes", notes);
command.ExecuteNonQuery();
}
conn.Close();
Console.WriteLine("connection is closed!!");
}

Related

Fetching Data from MySQL and Inserting it in MS SQL SERVER in visual studio c#

Am trying to read a table from a Mysql database and store all of it in a ms sql server in c# am reading from mysql correctly my problem is how to store the data i read in ms sql in the second part of code
string constring= ConfigurationManager.ConnectionStrings["cnxMysql"].ConnectionString;
MySqlConnection conn = new MySqlConnection(constring);
MySqlCommand cmd = new MySqlCommand("SELECT * FROM i_evt WHERE Updt=0",conn);
conn.Open();
cmd.ExecuteNonQuery();
string constring2 = ConfigurationManager.ConnectionStrings["cnxsql"].ConnectionString;
SqlConnection conn2 = new SqlConnection(constring2);
SqlCommand cmd2 = new SqlCommand("INSERT INTO i_evt",conn2);
conn2.Open();
cmd2.ExecuteNonQuery();
conn2.Close();
conn.Close();
I have a reverse issue, I have to transfer data from MS SQL Server to MySQL.
I have used below snippet for this, but I personally don't recommend this for production as it adds data one by one row. But you can use it for a small dataset or local environment. You can add a try-catch as well as customize as per your need. This is for just reference.
public void Main()
{
var table = GetDataTableFromSQLServer();
AddToMySQL(table);
}
private DataTable GetDataTableFromSQLServer()
{
var connection = GetSqlServerConnection();
string query = "SELECT Column1, Column2 FROM TableName WHERE Column3 is NOT NULL";
var command = new SqlCommand(query, connection);
connection.Open();
var reader = command.ExecuteReader();
DataTable table = new DataTable();
table.Load(reader);
connection.Close();
return table;
}
private void AddToMySQL(DataTable table)
{
var connection = GetMySQLConnection();
connection.Open();
string query = "INSERT INTO TableName (column1, column2) VALUES(#column1, #column2);";
int i = 0;
foreach (DataRow row in table.Rows)
{
if (i % 1000 == 0)
{
// Closing & Reopening connection after 1000 records
connection.Close();
connection.Open();
}
Console.WriteLine($"Adding ({++i}/{table.Rows.Count})");
MySqlCommand command = new MySqlCommand(query, connection);
command.Parameters.Add(new MySqlParameter("#column1", MySqlDbType.Int64) { Value = row.Field<long>("column1").Trim() });
command.Parameters.Add(new MySqlParameter("#column2", MySqlDbType.VarChar) { Value = row.Field<string>("column2").Trim() });
var affectedRows = command.ExecuteNonQuery();
}
connection.Close();
}
private SqlConnection GetSqlServerConnection()
{
string connectionString = #"Data Source=...";
SqlConnection connection = new SqlConnection(connectionString);
return connection;
}
private MySqlConnection GetMySQLConnection()
{
MySqlConnectionStringBuilder connectionBuilder = new MySqlConnectionStringBuilder
{
Server = "...",
Database = "...",
UserID = "...",
Password = "...",
Port = 3306
};
MySqlConnection connection = new MySqlConnection(connectionBuilder.ToString());
return connection;
}
Refer below code, you can optimize this code as there is alot of space for optimization but this is simple for beginner to understand basic level:
MySqlConnection conn = new MySqlConnection(constring);
MySqlCommand cmd = new MySqlCommand("SELECT * FROM i_evt WHERE Updt=0", conn);
conn.Open();
DataSet data;
using (MySqlDataAdapter sqlAdapter = new MySqlDataAdapter(mySqlCommand))
{
data = new DataSet();
sqlAdapter.Fill(data);
}
string constring2 = ConfigurationManager.ConnectionStrings["cnxsql"].ConnectionString;
SqlConnection conn2 = new SqlConnection(constring2);
conn2.Open();
for (int i = 0; i < data.Tables[0].Rows.Count; i++)
{
SqlCommand cmd2 = new SqlCommand("INSERT INTO i_evt(column1,column2) values(#col1,#col1)", conn2);
cmd2.Parameters.AddWithValue("col1", data.Tables[0].Rows[i][0].ToString());
cmd2.Parameters.AddWithValue("col12", data.Tables[0].Rows[i][1].ToString());
cmd2.ExecuteNonQuery();
}
conn2.Close();
conn.Close();

ASP.Net C# - Setting a MySQL query and parameters based on a condition

How do I go about setting a MySQL query and parameters based on a condition?
I want different queries based on 'questionSource' as shown below.
However, in my code below, 'cmd' does not exist in the current context.
Alternatively, I could have two different functions for each condition and call the necessary function as required but I imagine there must be a way to have conditions within a connection.
//validation checks
else
{
string connStr = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
MySqlConnection conn = new MySqlConnection(connStr);
string questionSource = Session["QuestionSource"].ToString();
string cmdText = "";
if (questionSource.Equals("S"))
{
cmdText += #"SELECT COUNT(*) FROM questions Q
JOIN users U
ON Q.author_id=U.user_id
WHERE approved='Y'
AND role=1
AND module_id=#ModuleID";
MySqlCommand cmd = new MySqlCommand(cmdText, conn);
cmd.Parameters.Add("#ModuleID", MySqlDbType.Int32);
cmd.Parameters["#ModuleID"].Value = Convert.ToInt32(Session["TestModuleID"]);
}
else if (questionSource.Equals("U"))
{
cmdText += "SELECT COUNT(*) FROM questions WHERE approved='Y' AND module_id=#ModuleID AND author_id=#AuthorID;";
MySqlCommand cmd = new MySqlCommand(cmdText, conn);
cmd.Parameters.Add("#ModuleID", MySqlDbType.Int32);
cmd.Parameters["#ModuleID"].Value = Convert.ToInt32(Session["TestModuleID"]);
cmd.Parameters.Add("#AuthorID", MySqlDbType.Int32);
cmd.Parameters["#AuthorID"].Value = Convert.ToInt32(Session["UserID"]);
}
int noOfQuestionsAvailable = 0;
int noOfQuestionsWanted = Convert.ToInt32(ddlNoOfQuestions.SelectedValue);
try
{
conn.Open();
noOfQuestionsAvailable = Convert.ToInt32(cmd.ExecuteScalar());
if (noOfQuestionsAvailable < noOfQuestionsWanted)
{
lblError.Text = "There are not enough questions available to create a test.";
}
else
{
Session["TestName"] = txtName.Text;
Session["NoOfQuestions"] = ddlNoOfQuestions.SelectedValue;
Session["QuestionSource"] = rblQuestionSource.SelectedValue;
Session["TestModuleID"] = ddlModules.SelectedValue;
Response.Redirect("~/create_test_b.aspx");
}
}
catch
{
lblError.Text = "Database connection error - failed to get module details.";
}
finally
{
conn.Close();
}
}
declare cmd before if
MySqlCommand cmd = new MySqlCommand("",connStr);
and in each part of if
cmd.CommandText=cmdText;
other suggestion: add
cmd.Parameters.Add("#ModuleID", MySqlDbType.Int32);
cmd.Parameters["#ModuleID"].Value = Convert.ToInt32(Session["TestModuleID"]);
always before if because it is used in the same way in if and else part
You just have to move the declaration of the cmd outside the if block:
//validation checks
else
{
string connStr = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
MySqlConnection conn = new MySqlConnection(connStr);
string questionSource = Session["QuestionSource"].ToString();
string cmdText = "";
MySqlCommand cmd; // <-- here
if (questionSource.Equals("S"))
{
cmdText += #"SELECT COUNT(*) FROM questions Q
JOIN users U
ON Q.author_id=U.user_id
WHERE approved='Y'
AND role=1
AND module_id=#ModuleID";
cmd = new MySqlCommand(cmdText, conn); // remove MySqlCommand here
cmd.Parameters.Add("#ModuleID", MySqlDbType.Int32);
cmd.Parameters["#ModuleID"].Value = Convert.ToInt32(Session["TestModuleID"]);
}
else if (questionSource.Equals("U"))
{
cmdText += "SELECT COUNT(*) FROM questions WHERE approved='Y' AND module_id=#ModuleID AND author_id=#AuthorID;";
cmd = new MySqlCommand(cmdText, conn); // remove MySqlCommand here
cmd.Parameters.Add("#ModuleID", MySqlDbType.Int32);
cmd.Parameters["#ModuleID"].Value = Convert.ToInt32(Session["TestModuleID"]);
cmd.Parameters.Add("#AuthorID", MySqlDbType.Int32);
cmd.Parameters["#AuthorID"].Value = Convert.ToInt32(Session["UserID"]);
}
int noOfQuestionsAvailable = 0;
int noOfQuestionsWanted = Convert.ToInt32(ddlNoOfQuestions.SelectedValue);
try
{
conn.Open();
noOfQuestionsAvailable = Convert.ToInt32(cmd.ExecuteScalar());
if (noOfQuestionsAvailable < noOfQuestionsWanted)
{
lblError.Text = "There are not enough questions available to create a test.";
}
else
{
Session["TestName"] = txtName.Text;
Session["NoOfQuestions"] = ddlNoOfQuestions.SelectedValue;
Session["QuestionSource"] = rblQuestionSource.SelectedValue;
Session["TestModuleID"] = ddlModules.SelectedValue;
Response.Redirect("~/create_test_b.aspx");
}
}
catch
{
lblError.Text = "Database connection error - failed to get module details.";
}
finally
{
conn.Close();
}
}
Just move the declaration of the MySqlCommand outside the if/else blocks so you could use it in the final try where you execute the command
//validation checks
else
{
string connStr = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
using(MySqlConnection conn = new MySqlConnection(connStr))
using(MySqlCommand cmd = conn.CreateCommand())
{
// Don't need to associate the command to the connection
// Already done by the CreateCommand above, just need to set
// the parameters and the command text
if (questionSource.Equals("S"))
{
cmdText = #"....."
cmd.CommandText = cmdText;
....
}
else if (questionSource.Equals("U"))
{
cmdText = "........."
cmd.CommandText = cmdText;
....
}
try
{
conn.Open();
noOfQuestionsAvailable = Convert.ToInt32(cmd.ExecuteScalar());
....
}
}
}
Notice also that you should use the using statement to be sure that your connection and your command are propertly closed and disposed.

How to remove the sql injection from this query and make it working well?

I am a new ASP.NET developer and I am developing a web-based application in which there is a menu bar that has many options. Some of these options will be displayed only to the Admin. There is a logic behind the system to check whether the user is an admin or not. If yes, the options will be displayed. I wrote the method but I have a sql injectiom and I want to remove it.
For your information, I have the following database design:
Users table: NetID, Name, Title
Admins table: ID, NetID
Here's the C# method:
private bool isAdmin(string username)
{
string connString = "Data Source=appSever\\sqlexpress;Initial Catalog=TestDB;Integrated Security=True";
string cmdText = "SELECT ID, NetID FROM dbo.Admins WHERE NetID = '" + NetID + "')";
using (SqlConnection conn = new SqlConnection(connString))
{
conn.Open();
// Open DB connection.
using (SqlCommand cmd = new SqlCommand(cmdText, conn))
{
SqlDataReader reader = cmd.ExecuteReader();
if (reader != null)
if (reader.Read())
if (reader["ID"].Equals(1))
return true;
return false;
}
}
}
I tried to change it by doing the changing the third line to:
string cmdText = "SELECT ID, NetID FROM dbo.Admins WHERE NetID = #NetID)";
But I got the following error and I don't know why:
Must declare the scalar variable "#NetID".
Could you please help me in solving this?
**UPDATE:
After updating the code to the following:
private bool isAdmin(string username)
{
string NetID = username;
string connString = "Data Source=appServer\\sqlexpress;Initial Catalog=TestDB;Integrated Security=True";
string cmdText = "SELECT ID, NetID FROM dbo.Admins WHERE NetID = #NetID";
using (SqlConnection conn = new SqlConnection(connString))
{
conn.Open();
// Open DB connection.
using (SqlCommand cmd = new SqlCommand(cmdText, conn))
{
cmd.Parameters.AddWithValue("#NetID", NetID);
SqlDataReader reader = cmd.ExecuteReader();
if (reader != null)
if (reader.Read())
if (reader["NetID"] == username)
return true;
return false;
}
}
}
I got the following error:
Incorrect syntax near ')'.
How to fix this problem?
You need to pass a value for your #NetID parameter:
cmd.Parameters.AddWithValue("#NetID", NetID);
Try this
private bool isAdmin(string username)
{
string connString = "Data Source=appSever\\sqlexpress;Initial Catalog=TestDB;Integrated Security=True";
string cmdText = "SELECT ID, NetID FROM dbo.Admins WHERE NetID = #NetID)";
using (SqlConnection conn = new SqlConnection(connString))
{
conn.Open();
// Open DB connection.
using (SqlCommand cmd = new SqlCommand(cmdText, conn))
{
cmd.Parameters.AddWithValue("#NetID", NetID);
SqlDataReader reader = cmd.ExecuteReader();
if (reader != null)
if (reader.Read())
if (reader["ID"].Equals(1))
return true;
return false;
}
}
}
If you use NetId as parameter in the IsAdmin method than it would help
private bool isAdmin(string NetID)
{
string connString = "Data Source=appSever\\sqlexpress;Initial Catalog=TestDB;Integrated Security=True";
string cmdText = "SELECT ID, NetID FROM dbo.Admins WHERE NetID = #NetID)";
using (SqlConnection conn = new SqlConnection(connString))
{
conn.Open();
// Open DB connection.
using (SqlCommand cmd = new SqlCommand(cmdText, conn))
{
cmd.Parameters.AddWithValue("#NetID", NetID);
string value = cmd.ExecuteScalar().tostring();
if (value != null)
return true;
else
return false;
}
}
}
Its better to use
cmd.Parameters.Add("#netid",SqlBdType.Int).Value=NetID;

Inserting into database from textbox in C# using parameters

I am a newbie to c#. I am trying to insert the values from the text box into the table in my database.
Table Name : address
Fields : name(varchar(50)),
age(int),
city(nchar(10))
When i try to retrieve the values from the database it is working perfectly.
Here is my code. Please help me rectify it.
string s = #"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True;User Instance=True";
SqlConnection a = new SqlConnection(s);
a.Open();
SqlCommand comm = new SqlCommand("INSERT INTO [address](name,age,city) VALUES(#na,#ag,#ci)");
string na = textBox1.Text;
int ag = int.Parse(textBox2.Text);
string ci = textBox3.Text;
comm.Parameters.Add("#na", System.Data.SqlDbType.VarChar,50).Value = na;
comm.Parameters.Add("#ag", System.Data.SqlDbType.Int).Value = ag;
comm.Parameters.Add("#ci", System.Data.SqlDbType.NChar,10).Value = ci;
comm.Connection = a;
comm.ExecuteNonQuery();
MessageBox.Show("okay");
a.Close();
The values are not reflected in the database.
try with this code :
string connectionString = "Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True;User Instance=True";
using (SqlConnection connection = new SqlConnection(connectionString))
{
using (SqlCommand insertCommand = connection.CreateCommand())
{
insertCommand.CommandText = "INSERT INTO address(name,age,city) VALUES (#na,#ag,#ci)";
insertCommand.Parameters.Add("#na", na);
insertCommand.Parameters.Add("#ag", ag);
insertCommand.Parameters.Add("#ci", ci);
insertCommand.Connection.Open();
insertCommand.ExecuteNonQuery();
}
}

insert data to table based on another table C#

I wrote some code that takes some values from one table and inserts the other table with these values.(not just these values, but also these values(this values=values from the based on table))
and I get this error:
System.Data.OleDb.OleDbException (0x80040E10): value wan't given for one or more of the required parameters.`
here's the code. I don't know what i've missed.
string selectedItem = comboBox1.SelectedItem.ToString();
Codons cdn = new Codons(selectedItem);
string codon1;
int index;
if (this.i != this.counter)
{
//take from the DataBase the matching codonsCodon1 to codonsFullName
codon1 = cdn.GetCodon1();
//take the serialnumber of the last protein
string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;" +
"Data Source=C:\\Projects_2012\\Project_Noam\\Access\\myProject.accdb";
OleDbConnection conn = new OleDbConnection(connectionString);
conn.Open();
string last= "SELECT proInfoSerialNum FROM tblProInfo WHERE proInfoScienceName = "+this.name ;
OleDbCommand getSerial = new OleDbCommand(last, conn);
OleDbDataReader dr = getSerial.ExecuteReader();
dr.Read();
index = dr.GetInt32(0);
//add the amino acid to tblOrderAA
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
string insertCommand = "INSERT INTO tblOrderAA(orderAASerialPro, orderAACodon1) "
+ " values (?, ?)";
using (OleDbCommand command = new OleDbCommand(insertCommand, connection))
{
connection.Open();
command.Parameters.AddWithValue("orderAASerialPro", index);
command.Parameters.AddWithValue("orderAACodon1", codon1);
command.ExecuteNonQuery();
}
}
}
EDIT:I put a messagebox after that line:
index = dr.GetInt32(0);
to see where is the problem, and I get the error before that. I don't see the messagebox
Your SELECT Command has a syntax error in it because you didn't enclose it with quotes.
Change this:
string last = "SELECT proInfoSerialNum FROM tblProInfo WHERE proInfoScienceName = "+this.name ;
OleDbCommand getSerial = new OleDbCommand(last, conn);
OleDbDataReader dr = getSerial.ExecuteReader();
to
string last = "SELECT proInfoSerialNum FROM tblProInfo WHERE proInfoScienceName = ?";
OleDbCommand getSerial = new OleDbCommand(last, conn);
getSerial.Parameters.AddWithValue("?", this.name);
OleDbDataReader dr = getSerial.ExecuteReader();
This code is example from here:
string SqlString = "Insert Into Contacts (FirstName, LastName) Values (?,?)";
using (OleDbConnection conn = new OleDbConnection(ConnString))
{
using (OleDbCommand cmd = new OleDbCommand(SqlString, conn))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("FirstName", txtFirstName.Text);
cmd.Parameters.AddWithValue("LastName", txtLastName.Text);
conn.Open();
cmd.ExecuteNonQuery();
}
}
Try to do the same as in the example.

Categories

Resources