Inserting into database from textbox in C# using parameters - c#

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();
}
}

Related

C# SQL Connection not found

How can I connect a SQL database in C#?
My code:
const string connectionString = "Data Source=127.0.0.1;User ID=root;Database=MyDatabase;Password=MyPassword";
var conn = new SqlConnection(connectionString);
conn.Open();
conn.Close();
I get: Error: 40 - could not open a connection to sql server. I tried also in Python and it worked well:
cnx = mysql.connector.connect(user='root', password='MyPassword', host='127.0.0.1', database='MyDatabase')
cursor = cnx.cursor()
What am I missing in C#?
Please use MySqlConnection for MySql DB.
const string connectionString = "Data Source=127.0.0.1;User ID=root;Database=MyDatabase;Password=MyPassword";
MySqlConnection conn = new MySqlConnection(connectionString );
conn.Open();
string sqlcommand = "SELECT Query";
MySqlCommand cmd = new MySqlCommand(sqlcommand , conn);
please follow this example
using MySql.Data.MySqlClient;
var connectionString = "server=serveradress;database=dbName;user id=sqluser;password=abc;";
using (var connection = new MySqlConnection(connectionString))
{
connection.Open();
using var command = new MySqlCommand("SELECT COUNT(*) FROM tableName ", connection);
var Count = command.ExecuteScalar();
Console.WriteLine($"There are {Count } movies");
}
server adress in general is 127.0.0.1 ,if you are working locally
here the source page :
example
and also consider reading this page here docs

Code deleting from datagrid but not in database

My code works in deleting information from the datagrid but does not delete it from the actual database. I am not sure how to fix this. Can i have some assistance please.
MySqlConnection sqlConnection = new MySqlConnection();
MySqlCommand sqlCommand = new MySqlCommand();
DataTable sqlData = new DataTable();
MySqlDataAdapter SqlAdapter = new MySqlDataAdapter();
DataSet sqlSet = new DataSet();
MySqlDataReader sqlDataReader;
//int dmlInfo;
String queried;
String server = "localhost";
String username = "root";
String password = "";
String database = "premiercare";
sqlConnection.Open();
sqlCommand.Connection = sqlConnection;
//removes from database (work to be done)
sqlCommand.CommandText = "Delete from premiercare.addpatient where id = #id";
sqlCommand = new MySqlCommand(queried, sqlConnection);
sqlConnection.Close();
//removes from dataGrid
foreach (DataGridViewRow items in this.dgAddPat.SelectedRows)
{
dgAddPat.Rows.RemoveAt(items.Index);
}
foreach (Control con in gbAddPat.Controls)
{
if (con is TextBox)
((TextBox)con).Clear();
}
loadInfo();
}
You need to make sure the connection and the queryString are correct and then you could do it like this:
//todo: make sure the connectionString is right
using (SqlConnection connection = new SqlConnection(connectionString))
{
//todo: build the right queryString
SqlCommand command = new SqlCommand(queryString, connection);
command.Connection.Open();
command.ExecuteNonQuery();
}
//no need to close the connection because of "using"

Update SQL table using 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!!");
}

How to insert record into a sql server express database table?

I'm trying to insert a textbox value to a database table called site_list.
The site_list table contains two columns id and site_name, id set to auto increment
This is the code I'm trying and when it execute there is no error, but the data is not showing up in the table
SqlConnection conn = new SqlConnection();
conn.ConnectionString =
"Data Source=.\\SQLExpress;" +
"User Instance=true;" +
"Integrated Security=true;" +
"AttachDbFilename=|DataDirectory|scraper_db.mdf;";
SqlCommand addSite = new SqlCommand("INSERT INTO site_list (site_name) "
+ " VALUES (#site_name)", conn);
addSite.Parameters.Add("#site_name", SqlDbType.NVarChar).Value = textBox1.Text;
conn.Open();
addSite.ExecuteNonQuery();
conn.Close();
Any help would be appreciated.
Regards
Edit:
This code started to work
string connstring = "Data Source=.\\SQLExpress;"+
"Integrated Security=true;"+
"User Instance=true;"+
"AttachDBFilename=|DataDirectory|scraper_db.mdf;"+
"Initial Catalog=scraper_db";
using (SqlConnection connection = new SqlConnection(connstring))
{
connection.Open();
SqlCommand addSite = new SqlCommand("INSERT INTO site_list (site_name)"+
"VALUES (#site_name)", connection);
addSite.Parameters.AddWithValue("#site_name", textBox1.Text);
addSite.ExecuteNonQuery();
connection.Close();
}
as people suggests, try creating the database on the server (it will be even easier to handle using Sql Management Studio).
Once that's done, try the following (just tested and it works):
using (SqlConnection conn = new SqlConnection(#"Persist Security Info=False;Integrated Security=true;Initial Catalog=myTestDb;server=(local)"))
{
SqlCommand addSite = new SqlCommand(#"INSERT INTO site_list (site_name) VALUES (#site_name)", conn);
addSite.Parameters.AddWithValue("#site_name", "mywebsitename");
addSite.Connection.Open();
addSite.ExecuteNonQuery();
addSite.Connection.Close();
}
try
{
using (SqlConnection conn = new SqlConnection(#"Persist Security Info=False;Integrated Security=true;Initial Catalog=myTestDb;server=(local)\SQLEXPRESS;database=Inventory;Data Source=localhost\SQLEXPRESS;"))
{
SqlCommand addSite = new SqlCommand(#"INSERT INTO Creation (Name,Product,Quantity,Category) VALUES (#Name,#Product,#Quantity,#Category)", conn);
addSite.Parameters.AddWithValue("#Name", textBox1.Text);
addSite.Parameters.AddWithValue("#Product", textBox2.Text);
addSite.Parameters.AddWithValue("#Quantity", textBox3.Text.ToString());
addSite.Parameters.AddWithValue("#Category", textBox4.Text);
thisConnection.Open();
addSite.ExecuteNonQuery();
}
}
catch
{
thisConnection.Close();
}
try this out :
string sql = String.Format("INSERT INTO site_list (site_name) VALUES('{0}')", myTextBox.Text);
using(SqlConnection connection = new SqlConnection(myConnectionString))
{
connection.open();
using(SqlCommand cmd = new SqlCommand(sql, connection))
{
cmd.ExecuteNonQuery();
}
}
Good luck
Try storing your textbox value in a variable. As in:
#stringname = textbox1.text
addSite.Parameters.Add("#site_name", SqlDbType.NVarChar).Value = #stringname;
(IMPORTANT! the # in #stringname is not necessary, but protects you against hackers!)
This code has worked wonders for me.
My apologies. The answer I gave previously will not work because the variable name used in the insert command (in your case #site_name) must match the variables used in your sqlcommand. As in:
#site_name = textbox1.text
addSite.Parameters.Add("#site_name", SqlDbType.NVarChar).Value = textBox1.Text;
Sorry for the confusion I might have caused.

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