Data insertion not happening in a database - c#

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.

Related

Open a connection to a local DB asp.net MVC

I'm trying to open a connection to a DB and then insert a record into a table. At the moment it's just a simple localDB, I have looked at opening the connection with the sqlclient namespace methods.
SqlConnection con = new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB;
AttachDbFilename=C:\\FILE\\PATH\\EXAMPLE\\TechMVCDB.mdf;Integrated Security=True;
Connect Timeout=30");
I'm not certain that my connection string is even correct, I got it directly from the connection string box when you click on your database in the server explorer panel. I added a breakpoint in the code after the connection was opened and a select all statement was executed :
SqlConnection con = new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=C:\\FILE\\PATH\\EXAMPLE\\TechMVCDB.mdf;Integrated Security=True;Connect Timeout=30");
con.Open();
SqlCommand com = new SqlCommand();
com.Connection = con;
com.CommandText = "SELECT * FROM Table ORDER BY Id";
SqlDataReader rdr = com.ExecuteReader();
I then get this error "System.Data.SqlClient.SqlException: 'Incorrect syntax near the keyword 'Table'.'" Table was just simply the name of the table was it also treating it as a keyword?
After this I changed the tablename to TechTester and ran it again, it ran with no errors and seemed to get the correct field amount of 4 id,sequence,direction,time it didn't seem to get the inserted test data.
I've also looked at using the Entity framework and implemented the very beginnings of it so I have my entity model class setup but nothing more. Is this the direction I should actually go with? How would I access the entity database?
My question is How do I best open a connection to a local db in asp.net-MVC using C#?
Table is one of the SQL Server reserved keywords.

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?

Connection string for C# winapp with a SQL Server database file

This is not the first time I have used databases using the C# in asp.net, but I can't seem to make it work in a Winforms app.
This is a test face, so there is not a real database but a SQL Server database file that I created.
What I have is this:
public AddControl SaveResearcher(string name)
{
using(SqlConnection conn = new SqlConnection("")){
SqlCommand cmd = new SqlCommand("INSERT INTO Personell VALUES (#name, #function)", conn);
cmd.Parameters.Add("name",SqlDbType.VarChar).Value = name;
cmd.Parameters.Add("function", SqlDbType.VarChar).Value = "Researcher";
conn.Open();
cmd.ExecuteNonQuery();
}
return AddControl.OK;
}
What do I have to put in the connection string?
Thanks in advance.
The connection string for at sql server db file without username/password
Server=.\SQLExpress;AttachDbFilename=c:\pathtodb\mydbfile.mdf;Database=dbname; Trusted_Connection=Yes;
You may find more connection string options at
http://www.connectionstrings.com/sql-server-2008
You can check there,
Connection strings for SQL Server 2005
Do you mean soemthing like this?
"Data Source[SERVER_NAME];Initial Catalog=[DATABASE_NAME];Integrated Security=True;MultipleActiveResultSets=True"
connectionString="Data Source=computerName\sqlexpress;Initial Catalog=DatabaseName;Integrated Security=True"

insert problem in C#, using sqlcommand

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

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