insert problem in C#, using sqlcommand - c#

when I run this sql:
insert into table1(ID,Name) values ('10','Saeed');
it seems that the record has been inserted, and if I read the table using (select * from table1) it shows me the inserted record, but after closing the program, it disappears.
it's the code:
string constr="Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|" +
"\\Database1.mdf;Integrated Security=True;User Instance=True";
SqlConnection con = new SqlConnection(constr);
con.Open();
SqlCommand cmd = new SqlCommand(
"insert into st (ID,Name) values ('10','saeed');", con);
cmd.ExecuteNonQuery();
cmd.Close();
I inserted some records in it manually, and when I read the database, the manually inserted records exist.
It is not a transaction problem wont be solved with a transaction!

The issue sounds like you started a transaction and forgot to commit it. However, if you are using the exact code you posted this is not a transaction problem because you are not using one.
That makes me think there is something funky going on with your connection string.
For kicks and giggles trying changing your connection string to something like this
Server=myServerName\theInstanceName;Database=myDataBase;Trusted_Connection=True;

Guess:
You are working with SQL Server Express and "Database1.mdf" within your project is configured (in properties window) for "Copy to Output Directory" value "Always"

Try to specify: "Initial Catalog=InstanceDB;" as well to make sure it does not create a new db name when you restart the application.

error in your code itself
its
con.Close();
not
cmd.Close();
there is no close method for SqlCommand

I agree with pascal. Sounds like the transaction isn't being committed.
(Edited to provide clearer code block from my Comment below)
con.Open();
trans = con.BeginTransaction();
SqlCommand cmd = new SqlCommand( "insert into st (ID,Name) values ('10','saeed');", con);
cmd.ExecuteNonQuery();
tran.Commit();

Related

C#: Inserting data in MySQL in UTF-8 programmatically

I am writing a winforms program that gradually inserts into and reads from a MySQL database.
In PHPMyAdmin the fields I insert into are set to utf8_general_ci, and if I insert a row in the MyAdmin interface, it works perfectly. However, if I insert data on-the-fly using my program, certain special characters, like 'Ő' and 'Ű' are saved in the database as 'O' and 'U' respectively.
This is the code I am using:
MySqlConnection conn;
conn = new MySql.Data.MySqlClient.MySqlConnection();
conn.ConnectionString = sql_string;
conn.Open();
MySqlCommand cmd = new MySqlCommand("", conn);
cmd.CommandText = "INSERT INTO projects (Projects_comment) VALUES (#Projects_comment)";
cmd.Parameters.AddWithValue("#Projects_comment", "ŐŰ");
cmd.ExecuteNonQuery();
conn.Close();
This however, appears as "OU" in the database. I believe the problem is with visual studio's coding. How can I change it, or how to resolve this problem?

the requested operation requires sql clr context

I am getting an error while connecting to the sql from my cs file. I am trying to create CLR functions in c# without using any IDE which is the requirement. I need to access the database to get some value. Following is the code to connect to my database in c#.
using (SqlConnection conn = new SqlConnection("context connection=true"))
{
conn.Open();
SqlCommand cmd = new SqlCommand(
"SELECT COUNT(*) AS 'Order Count' FROM customer_master with (nolock)", conn);
SqlContext.Pipe.ExecuteAndSend(cmd);
return (int)cmd.ExecuteScalar();
}
but I am getting the following error:
"The requested operation requires a SqlClr context, which is only available when running in the Sql Server process". If i use pipe i don't know how to convert that to an int value. Any suggestions please....
As per this Blog post, try it like this, with the SQLConnection not in a using. The SQLCommand is Disposable and should be in a using though.
SqlConnection conn = new SqlConnection("context connection=true") ;
using(SqlCommand cmd = new SqlCommand(
"SELECT COUNT(*) AS 'Order Count' FROM customer_master with (nolock)", conn))
{
conn.Open();
return (int)cmd.ExecuteScalar();
}
I wrote the below first, but I think the above is the answer, I'm leaving struck out in case it is relevant.
A ContextConnection is a connection back down the existing open connection that the SQL calling the CLR function is using.
To use a SQL CLR Function with a ContextConnection you have to call it from inside a SQL Statement.
e.g. (where CLRConvert is my CLR function that connects back to my database and performs a query and converts stuff).
select dbo.CLRConvert(Data) from MyTables;
If you need to call it outside of here, you will need a proper connection string.

Data insertion not happening in a database

I'm trying to insert data into a database. the connection is working fine. However I can't insert data and I have no idea why. The table is just not getting updated.
string ConnectionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename=C:\\Users\\Kaushalya\\Documents\\NewAgain.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True";
SqlCommand cmd = new SqlCommand("Insert into Tabel1(name) VALUES (#UserName);",conn);
cmd.Parameters.Add(new SqlParameter("#UserName", Convert.ToInt32(0)));
Connection when tested is working fine. However, I can't do anything with the database.
You need to execute the Command object.
cmd.ExecuteNonQuery();
More info here.
You need to call ExecuteNonQuery() to run the query.

OleDB not saved to database file

I have an MDB file I access using OleDB:
OleDbConnection connection = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\Database.mdb;Persist Security Info=True");
And try to create a new row in a table Users:
connection.Open();
OleDbCommand cmd = new OleDbCommand("INSERT INTO `users` (`name`, `password`) VALUES ('asd', 'asd')", connection);
cmd.ExecuteNonQuery();
connection.Close();
But nothing happens. I don't get an error message or exceptions, it runs without problems. But when I check the database after the program finished, the table still is empty.
(I already tried the same using DataSets and TableAdapters, but the same happened there: Inserting not committed to database)
That query does not look like an Access query. Have you tried:
"INSERT INTO [users] ([name], [password]) VALUES ('asd', 'asd')"
In Access, table and field names do not use a back-quote, however, reserved words must be enclosed in square brackets.

Query Hangs

Ok, this seems simple but I can't find a solution to save my life. I am trying to do a very simple INSERT query on an Oracle DB. I can log into the DB in TOAD with the same credentials as I use in the code and run the INSERT with no problem, so as near as I can tell there are no permissions issues with the credentials and the query itself is syntacticly correct. When I try to run the below code, it just hangs. No errors or anything. I can see the session pop up in TOAD so as far as I can tell the code establishes the connection with no problem. Here is the code:
String connStr = "Data Source=DB;User id=<USER>;Password=<PASSWORD>;";
String query = "INSERT INTO table (fields) VALUES (values)";
OracleConnection conn = new OracleConnection(connStr);
conn.Open();
OracleCommand cmd = conn.CreateCommand();
cmd.CommandText = query;
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
conn.Close();
conn.Dispose();
I have also tried using an ADO connection and got the same result. Any ideas are appreciated.
Have you committed or rolled back the transaction in Toad? Your application could be waiting on a lock held by your session created by Toad.
Have you tried wrapping it in a transaction and explicitly committing after the insert? IIRC, Oracle's default semantics are very transaction-oriented, unlike SQL Server's.

Categories