Insert data into local database using ado.net in a console application - c#

Here is what I have written so far.There is no exception so I am assuming the connection is working fine but no data is inserted into the database table. Please tell me what is wrong with my code
SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["MyETL.Properties.Settings.connectionStr"].ConnectionString);
try
{
conn.Open();
// foreach (student stu in stulist)
// {
string strQuery = "INSERT INTO Student(Sid,st_name) VALUES (#id,#name)";
SqlCommand cmd = new SqlCommand(strQuery, conn);
cmd.Connection = conn;
cmd.Parameters.AddWithValue("#id", "111");
cmd.Parameters.AddWithValue("#name", "nallia");
cmd.ExecuteNonQuery();
}
catch
{
conn.Close();
}

Try this
static void Insert()
{
try
{
string connectionString =System.Configuration.ConfigurationManager.ConnectionStrings["MyETL.Properties.Settings.connectionStr"].ConnectionString;
using (SqlConnection conn =new SqlConnection(connectionString))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand("INSERT INTO Student(Sid,st_name) VALUES (" +
"#id,#name)", conn))
{
cmd.Parameters.AddWithValue("#Id", 111);
cmd.Parameters.AddWithValue("#Name", "nallia");
int rows = cmd.ExecuteNonQuery();
//rows number of record got inserted
}
}
}
catch (SqlException ex)
{
//Log exception
//Display Error message
}
}

It has been nearly 2,5 years but if you haven't still solved this problem, you should change the "copy to output directory" attribute to "copy if newer". Your database is changing but every time you start debugging, you read the initial version of database so, you see that there is no changes.

Related

Why doesn't my C# code update the SQL Server database although I get the correct number of affected rows

I created the following code:
public static bool setHeadword(int id, string headword)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\\pms.mdf;Integrated Security=True";
conn.Open();
SqlCommand command = new SqlCommand("UPDATE headwords SET Headword = #headword WHERE Id = #id", conn);
command.Parameters.AddWithValue("#headword", headword);
command.Parameters.AddWithValue("#id", id);
int result = command.ExecuteNonQuery();
conn.Close();
return true;
}
But the code doesn't work because the value in the database doesn't change.
If I run the code manually in the database the change takes place. But it won't work with C#.
Also the result variable are holding the right number of affected rows (1 in this case).
I'm not sure I have to flush the changes or something else.
Thanks for your help and best regards
Franz
static void Update(int id, string headword)
{
try
{
//You should create connectionString with correct details otherwise fail connection
string connectionString =
"server=.;" +
"initial catalog=employee;" +
"user id=sa;" +
"password=123";
using (SqlConnection conn =
new SqlConnection(connectionString))
{
conn.Open();
using (SqlCommand cmd =
new SqlCommand("UPDATE headwords SET Headword=#headword" +
" WHERE Id=#Id", conn))
{
cmd.Parameters.AddWithValue("#Id", id);
cmd.Parameters.AddWithValue("#headword", headword);
int rows = cmd.ExecuteNonQuery();
}
}
}
catch (SqlException ex)
{
//Handle sql Exception
}
}

Insert Data Into Databse Once User Clicks on Button

I am trying to write a code that will insert data into a database once user click on button. There's something wrong with the code and it does not seem to work properly. I connect to an external database based on my hosting provider.
private void druk_Click(object sender, EventArgs e)
{
MySql.Data.MySqlClient.MySqlConnection conn;
string myConnectionString;
myConnectionString = "server=s59.hekko.net.pl;uid=truex2_kuba;" +
"pwd=test;database=truex2_kuba;";
try
{
conn = new MySql.Data.MySqlClient.MySqlConnection(myConnectionString);
conn.Open();
MySqlCommand cmd = new MySqlCommand();
}
catch (MySql.Data.MySqlClient.MySqlException ex)
{
MessageBox.Show(ex.Message);
}
cmd.CommandText = "insert into [barcode]values(#class, #tree, #type, #amount, #length, #width, #square)";
cmd.Parameters.AddWithValue("#class", klasa.Text);
cmd.Parameters.AddWithValue("#tree", gatunek.Text);
cmd.Parameters.AddWithValue("#type", rodzaj.Text);
cmd.Parameters.AddWithValue("#amount", amount.Text);
cmd.Parameters.AddWithValue("#length", length.Text);
cmd.Parameters.AddWithValue("#width", width.Text);
cmd.Parameters.AddWithValue("#square", textBox1.Text);
int a = cmd.ExecuteNonQuery();
if (a > 0)
{
MessageBox.Show("Zapisane do raportu");
}
The issue is this:
MySqlCommand cmd = new MySqlCommand();
is in the scope of the try, catch block.
Further on in the code, there was a reference to the cmd variable which is null and hence no data goes in.
Move it outside of the try, catch block.

Cannot insert the data into the table C# visual studio 2013

i want to write data into a local database table.
When i run the code there are no erros and when i count the rows after the insert statement the message box shows me that a row was inserted.
But when i close the programm and look in my database there are no new rows.
I'm using C# and Visual Studio 2013.
Do anybody know what the problem is?
Thank you.
String connection = "Data Source=(LocalDB)\\v11.0;AttachDbFilename=|DataDirectory|\\Datenbank.mdf;Integrated Security=True;Connect Timeout=30";
SqlConnection cnn = new SqlConnection(connection);
cnn.Open();
String query = "INSERT INTO Customer (ID, Name) VALUES (#id, #name)";
SqlCommand command = new SqlCommand(query, cnn);
command.Parameters.AddWithValue("#id", 1);
command.Parameters.AddWithValue("#name", 'John');
SqlDataReader reader;
command.ExecuteNonQuery();
query = "Select count(ID) from Customer";
command = new SqlCommand(query, cnn);
reader = command.ExecuteReader();
while (reader.Read())
{
MessageBox.Show(reader[0].ToString());
}
reader.Close();
Try like this:
try {
int rowsAffected = command.ExecuteNonQuery();
if (0 < rowsAffected)
MessageBox.Show("Success!");
else
MessageBox.Show("Failed!");
} catch (SqlException ex) {
MessageBox.Show(ex.Message);
} finally {
if (cnn.State == ConnectionState.Open)
cnn.Close();
}
Also refer: Why saving changes to a database fails?

Error when updating in database

I am getting error on updating database in C#. Here is the code:
string connectionstring = "server=AMAN;database=student;Integrated Security=True";
SqlConnection conn;
string Admission_no = txtAddmissionNo.Text;
SqlCommand cmd;
conn = new SqlConnection(connectionstring);
conn.Open();
string query = "update fees set prospectues_fee=#prospectues_fee, registration_fee=#registration_fee,admission_fee=#admission_fee ,security_money=#security_money,misslaneous_fee=#misslaneous_fee,development_fee=#development_fee,transport_fair=#transport_fair,computer_fee=#computer_fee ,activity=#activity,hostel_fee=#hostel_fee,dely_fine=#dely_fine,back_dues=#back_dues,tution_feemonth=#tution_feemonth ,tution_fee=#tution_fee,other_fee=#other_fee,total=#total,deposit=#deposit,dues=#dues where Admission_no=#Admission_no";
cmd=new SqlCommand(query,conn);
cmd.Parameters.AddWithValue("#Admission_no", Admission_no);
cmd.Parameters.AddWithValue("#prospectues_fee", prospectues_fee);
cmd.Parameters.AddWithValue("#registration_fee", registration_fee);
cmd.Parameters.AddWithValue("#admission_fee", admission_fee);
cmd.Parameters.AddWithValue("#security_money", security_money);
cmd.Parameters.AddWithValue("#misslaneous_fee", misslaneous_fee);
cmd.Parameters.AddWithValue("#development_fee", development_fee);
cmd.Parameters.AddWithValue("#transport_fair", transport_fair);
cmd.Parameters.AddWithValue("#computer_fee", computer_fee);
cmd.Parameters.AddWithValue("#activity", activity);
cmd.Parameters.AddWithValue("#hostel_fee", hostel_fee);
cmd.Parameters.AddWithValue("#dely_fine", dely_fine);
cmd.Parameters.AddWithValue("#back_dues", back_dues);
cmd.Parameters.AddWithValue("#tution_fee", tution_fee);
cmd.Parameters.AddWithValue("#other_fee", other_fee);
cmd.Parameters.AddWithValue("#total", total);
cmd.Parameters.AddWithValue("#tution_feemonth", tution_feemonth);
cmd.Parameters.AddWithValue("#deposit", deposit_fee);
cmd.Parameters.AddWithValue("#dues", dues);
cmd = new SqlCommand(query, conn);
try
{
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
Error is #prospectues_fee scalar must be declared, which I have already declared.
The error is simpler than I thought:
cmd = new SqlCommand(query, conn);
... // lots of code
cmd = new SqlCommand(query, conn);
try
{
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
You are creating a second command just prior to executing it; this second command has the text but no parameters. Remove this second new SqlCommand line.
This sounds like the dreaded null vs DBNull issue. null in a parameter means "don't send this". Which is really really silly, but there we are. Try with:
cmd.Parameters.AddWithValue("#prospectues_fee",
((object)prospectues_fee) ?? DBNull.Value);
now repeat for all of the parameters... or just add a method that loops over them and checks them:
static void FixTheCrazy(DbCommand command) {
foreach(DbParameter param in command.Parameters) {
if(param.Value == null) param.Value = DBNull.Value;
}
}
Alternatively, use a tool like dapper that will do it for you:
using(varconn = new SqlConnection(connectionstring))
{
conn.Execute(query, new {
Admission_no, prospectues_fee, registration_fee, ...
deposit_fee, dues });
}

Error Executing Query on C#

i have question. I want to store data on my mysqldatabase using this C#
private void btnSaveFilm_Click(object sender, EventArgs e)
{
try
{
MySqlConnection conn = new MySqlConnection(connection.mysqlconnectionbuilder());
conn.Open();
MySqlCommand cmd = conn.CreateCommand();
cmd.CommandText = "INSERT INTO film(judul,genre,asal,kondisi)"
+ "VALUES(#judul,#genre,#asal,#kondisi)";
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#judul", textBoxJudul.Text);
cmd.Parameters.AddWithValue("#genre", category(comboBoxGenre.SelectedValue.ToString()).ToString());
cmd.Parameters.AddWithValue("#asal", asal(comboBoxAsal.SelectedValue.ToString()).ToString());
cmd.Parameters.AddWithValue("#kondisi", checkedStatus());
cmd.ExecuteNonQuery();
conn.Close();
}
catch(Exception exe)
{
Console.Write("Error on Save Film : " + exe.ToString() + "\n" +exe.Message);
}
}
but it shows error System.NullReferenceException: Object reference not set to an instance of an object.
Error at this line 40:
cmd.Parameters.AddWithValue("#genre",kategori(comboBoxGenre.SelectedValue.ToString()).ToString());
how to solve that?
refractor your code into this, use using statement,
string connString = connectionmysqlconnectionbuilder();
using (MySqlConnection conn = new MySqlConnection(connString)
{
using (MySqlCommand cmd = new MySqlCommand())
{
cmd.Connection = conn;
cmd.CommandText = #"INSERT INTO film(judul,genre,asal,kondisi)
VALUES(#judul,#genre,#asal,#kondisi)";
cmd.Parameters.AddWithValue("#judul", textBoxJudul.Text);
cmd.Parameters.AddWithValue("#genre", kategori(comboBoxGenre.Text).ToString());
cmd.Parameters.AddWithValue("#asal", asal(comboBoxAsal.Text).ToString());
cmd.Parameters.AddWithValue("#kondisi", checkedStatus());
try
{
comm.Open();
cmd.ExecuteNonQuery();
}
catch(MySqlException ex)
(
Console.WriteLine(ex.ToString());
)
}
}
you could also use
comboBoxGenre.Text instead of comboBoxGenre.SelectedValue
There can be two reasons:
1.comboBoxGenre.SelectedValue will be null
2.kategori() will be returning null
you can handle null error by using Convert.ToString() instead of variable.toString()
so use this instead also for other lines
cmd.Parameters.AddWithValue("#genre", Convert.ToString(kategori(Convert.ToString(comboBoxGenre.SelectedValue))));

Categories