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

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?

Related

Using ADO.NET how to insert list of data into SQL?

I have a list off data like
list=[{id:1,name:"ABC",age:12},{id:2,name:"QWE",age:21}]
I want to insert these data into database dynamically.
I googled and found how to insert a particular data. but dont know how to read the list andthen nsert those data.
string connetionString = null;
SqlConnection connection;
SqlCommand command;
string sql = null;
connetionString = "Data Source=source;Initial Catalog=testDB;User ID=ABCD;Password=password";
sql = "INSERT INTO TableName (id,name,age) VALUES('1','ABC',12)";
connection = new SqlConnection(connetionString);
try
{
connection.Open();;
command = new SqlCommand(sql, connection);
command.ExecuteNonQuery();
command.Dispose();
connection.Close();
}
catch (Exception ex)
{
Console.WriteLine("Can not open connection ! ");
}
cnx.Open(); // open cnx
if(List.Count !=0){ // if List isn't empty
for(int i = 0 i < List.Count ;i++)
{
// here he will execute one by one
string myQuery ="insert into TABLE_NAME values ('"+List[i][0]+"','"+List[i][1]+"','"+List[i][3]+"' ");
SqlCommand cmd = new SqlCommand(myQuery,cnx);
cmd.ExecuteNonQuery();
}
}
// i hope it's help you :))

Proper way of closing sql connection - without using MARS

My client server is not supporting MARS. So I need to close each sql connection after executing each query. But I have doubt on closing connection when its coming to multiple nested loop query .
My code is
protected void btn_upload_Click(object sender, ImageClickEventArgs e)
{
try
{
SqlConnection con = obj.getcon();
con.Open();
SqlCommand cmd77 = new SqlCommand("select * from emp_details where emp_id='"+emp_id+"'", con);
SqlDataReader dr77 = cmd77.ExecuteReader();
if (dr77.HasRows)//dont insert if employee already exist
{
string query1 = "UPDATE emp_details SET emp_name= #emp_name where emp_id=#emp_id";
SqlCommand cmd = new SqlCommand(query1, con);
cmd.Parameters.Add(new SqlParameter("emp_id", emp_id));
cmd.Parameters.Add(new SqlParameter("emp_name", emp_name))
cmd.ExecuteNonQuery();
}
else
{
insertdataintosql(GetempID,GetempName);
}
con.Close();
}
catch (Exception ex)
{
string ex=ex.Message;
}
}
public void insertdataintosql(string emp_id, string emp_name)
{
SqlConnection con = obj.getcon();
con.Open();
string query = "insert into emp_details(emp_id,emp_name) values(#emp_id,#emp_name)";
SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.Add(new SqlParameter("emp_id", emp_id));
cmd.Parameters.Add(new SqlParameter("emp_name", emp_name))
cmd.ExecuteNonQuery();
con.Close();
}
Where should I close the first connection for SqlDataReader (dr77) since it is used in if else loop? If not using MARS , Shall I need to open/close a new connection on update query? So is it necessary to close dr77 to before it?

C# - Access Database: Why SELECT * FROM table is not working?

A simple "select * from tablename" sql query works for a table named 'mode' but not for a table named 'user'. Why?
Both tables have 2 columns. If I run the program with the "mySQL" variable as "SELECT * FROM mode" it works fine. If I put the user table instead, which means the mySQL would have been "SELECT * FROM user" then it raises an exception which says "Syntax error in FROM clause.". How can this be?
Here is the code:
static void Main(string[] args)
{
String connectionstring = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=Accounts.mdb";
OleDbConnection conn;
conn = new OleDbConnection(connectionstring);
try
{
conn.Open();
}
catch (Exception)
{
Console.Write("Could not connect to database");
}
String mySQL = "SELECT * FROM user";
OleDbCommand cmd = new OleDbCommand(mySQL, conn);
OleDbDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
Console.Write(String.Format("{0}\n,{1}\n", rdr.GetValue(0).ToString(), rdr.GetValue(1).ToString()));
}
Console.Read();
}
Because USER is a reserved word in MS-Access
Change you query to encapsulate it between square brakets
SELECT * FROM [User]
albeit I suggest you to change the name of the table
Do like Steve said. And a suggestion for your code:
String connectionstring = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=Accounts.mdb";
OleDbConnection conn = null;
OleDbCommand cmd = null;
OleDbDataReader rdr = null;
String mySQL = "SELECT * FROM [user]";
try
{
conn = new OleDbConnection(connectionstring);
conn.Open();
cmd = new OleDbCommand(mySQL, conn);
rdr = cmd.ExecuteReader();
while (rdr.Read())
{
Console.Write(String.Format("{0}\n,{1}\n", rdr.GetValue(0).ToString(), rdr.GetValue(1).ToString()));
}
Console.Read();
conn.Close();
}
catch (Exception ex)
{
Console.Error.Write("Error founded: " + ex.Message);
}
finally
{
if (conn != null) conn.Dispose();
if (cmd != null) cmd.Dispose();
if (rdr != null) rdr.Dispose();
}

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

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.

Insert row into database from C# form

String ConString = #"DataSource=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\BizContact.mdf;Integrated Security=True;User Instance=True";
SqlConnection cn = new SqlConnection(ConString);
try
{
cn.Open();
MessageBox.Show("connect");
}
catch (Exception)
{
MessageBox.Show("Did not connect");
}
SqlCommand cmd = new SqlCommand("insert tableNote values (#UserName,#Note)",cn);
cmd.Parameters.AddWithValue("#UserName", textBox1.Text);
cmd.Parameters.AddWithValue("#Note", textBox2.Text);
try
{
int res = cmd.ExecuteNonQuery();
if (res > 0)
{
MessageBox.Show("insert");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
cn.Close();
}
I am trying to add new row to the database. The above code is correct with no error and it display the try statement but does not insert row into the database. Any idea to solve it.
try full T-SQL statement
"INSERT INTO table_name (userColumn, noteColumn) VALUES (#UserName, #Note)"
also dispose SqlConnection via using state
using(SqlConnection cn = new SqlConnection(ConString))
{
//....
}
Your insert statement is wrong (missing into). Do either:
insert into tableNote select #UserName,#Note
or
insert into tableNote (column_name1, column_name2) values (#UserName,#Note)
Open up Sql Profiler and watch it execute the command, then try replaying that command into Sql Management Studio. More than likely, it'll show you that the query is ever so slightly malformed such that it happily does nothing successfully.

Categories