C# OleDB SQL Insert Command - c#

I am trying implement a SQL INSERT command into my MS Access database using C# with Visual Studio 2012.
But after that, when I open my Access database, there is no updates even the insert command can be successfully created by showing the success pop-up window after executeNonQuery()
Would you please tell me how to make this insert into SQL command work?
This is my code
OleDbCommand cmd = new OleDbCommand();
cmd.CommandText = #"INSERT INTO STUDENT(CHI_NAME, ENG_NAME, NICK_NAME,
BD_YYYY, BD_MM, BD_DD,
HOME_TEL, NO_OF_CHILD, PARENT_EMAIL,
SEC_EMAIL, STUDENT_ADDR, DISTRICT,
MOTHER_NAME, MOTHER_TEL, MOTHER_OCCU,
FATHER_NAME, FATHER_TEL, FATHER_OCCU,
E_NAME, E_TEL, E_RELATIONSHIP, REMARKS)
VALUES(#NEW_CHI_NAME, #NEW_EN G_NAME, #NEW_NICK_NAME,
#NEW_BD_YYYY, #NEW_BD_MM .....);"
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#NEW_CHI_NAME", chi_name);
cmd.Parameters.AddWithValue("#NEW_ENG_NAME", eng_name);
cmd.Parameters.AddWithValue("#NEW_NICK_NAME", nick_name);
cmd.Parameters.AddWithValue("#NEW_BD_YYYY", bd_year);
cmd.Parameters.AddWithValue("#NEW_BD_MM", bd_month);
....
cmd.Connection = connection;
connection.Open();
cmd.Transaction = connection.BeginTransaction();
int rows= cmd.ExecuteNonQuery();
if(rows > 0)
{
MessageBox.Show("Insert New Client Success!");
}
else
{
MessageBox.Show("Insert New Client Failed!");
}
cmd.Transaction.Commit();
connection.Dispose();
connection.Close();

In Solution Explorer, right click your Access file, choose Properties, and set Copy To Output Directory to Copy if Newer

Go to the debug directory, you will find you accdb file copied there. Open it and verify.

Related

sqlite insert with c#

i am testing my sqlite local server with c#, I have the connection and query setup without problem. I tried to copy the query to sqlite and it runs without problem. However, when I run it in my program, nothing insert into the db. Wondering what the problem is.
I have set the db build action to Content, and the copy to output directory options to copy if newer
private void insertIntoDB(string query)
{
using (System.Data.SQLite.SQLiteConnection conn = new System.Data.SQLite.SQLiteConnection("data source=.\\VHTDatabase.db"))
{
using (System.Data.SQLite.SQLiteCommand cmd = new System.Data.SQLite.SQLiteCommand(conn))
{
conn.Open();
Console.WriteLine(query);
cmd.CommandText = query;
cmd.ExecuteNonQuery();
conn.Close();
}
}
}
Try a full path to your database in your Connectionstring
Then maybe try to add the CommandText before you open the Connection.
i mean:
cmd.CommandText = query;
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
Does your database give you informations with SELECT?
Maybe you need to reconfigure the User of the Database and give him rights to write, change and delete.
If nothing helps, then you can check, if it gives you an error.
try
{
cmd.CommandText = query;
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
catch(Exception ex)
{
Console.WriteLine(ex);
}

Doesn't save added value into database

In Visual Studio (2013) I have added service-based database (Database1.mdf) in my project. I have added in it a table, and via Show Data Table added two rows. Reading data from database works as required. But there is a problem with add value to database. If I while the program is running add value to database and then press "Reading data" it's ok, the data is reading. But If I while the program is still running go to "Show Data Table" and press button "update", I get the error: "This database cannot be imported. It is either an unsupported SQL Server verison or an unsopported database compatibility".
If I press button "update" in "SQL Server Object Explorer" and then go to "Show Data Table" and press button "update", the data is updates, but no added data. Also, after the completion of the program there isn't the added data.
Why?
I have tried to change the properties "Copy To Output Directory" from "Copy always" to "Do not Copy" or "Copy if newer". But it didn't help me. Please help me
Read data:
string strConnectionString = "Data Source=(LocalDB)\\v11.0;AttachDbFilename=|DataDirectory|\\Database.mdf;Integrated Security=True";
using (SqlConnection con = new SqlConnection(strConnectionString))
{
try
{
SqlCommand command = new SqlCommand("SELECT [Login] FROM [UsersTable];", con);
con.Open();
SqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
label1.Text = "Last value: " + reader.GetString(0);
}
}
}
catch (SqlException ex)
{
}
Add data:
string strConnectionString = "Data Source=(LocalDB)\\v11.0;AttachDbFilename=|DataDirectory|\\Database.mdf;Integrated Security=True";
using (SqlConnection con2 = new SqlConnection(strConnectionString))
{
using (SqlCommand command2 = new SqlCommand())
{
command2.Connection = con2;
command2.CommandType = CommandType.Text;
command2.CommandText = "INSERT INTO [UsersTable] ([Login], [Password]) VALUES (#Login, #Password)";
command2.Parameters.AddWithValue("#Login", textLogin.Text);
command2.Parameters.AddWithValue("#Password", textPassword.Text);
try
{
con2.Open();
command2.ExecuteNonQuery();
}
catch (SqlException)
{
// error here
}
finally
{
con2.Close();
}
}
}
Update
Perhaps the example isn't clear enough for you.
private void SubmitNote(string message)
{
// Ensure parameter isn't null.
if(string.IsNullOrEmpty(message))
return;
// Our Insert Query:
string insert = #"INSERT INTO [Notes] ([Username], [Date], [Message])
VALUES (#Username, #Date, #Message);";
// Define our Connection & Command:
using(SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["db"].ConnectionString))
using(SqlCommand command = new SqlCommand(insert, connection))
{
// Open Connection
connection.Open();
// Define our Command (AddWithValue / Add Approach)
command.Parameters.Add("#Username", SqlDbType.VarChar, 50).Values = User.Identity.Name;
command.Parameters.AddWithValue("#Date", DateTime.Now);
command.Parameters.Add("#Message", SqlDbType.VarChar).Value = message;
// Execute Query:
command.ExecuteNonQuery();
}
}
So anytime I'd like to insert a message to the database I simply call:
SubmitNote("What is love, baby don't hurt me.");
That would execute without any issues, assuming the parameter and connection are valid. You could write an exception helper, but that is above and beyond your issue. One of the problems your potentially having is:
Parameter may be Null
An issue within your Command Text
Potential issue with your Connection String.
Based on the issue you mentioned, a value is Null which means it doesn't contain a valid value. For instance if you do:
String message = String.Empty;
SubmitNote(message);
That would fail, as message doesn't have a value. Hopefully this helps.

Error with path of Compact Database .sdf in the client computer

I want to publish my project with compact database but I have an error message that says: the path is not exists, I solved it by write this code:
SqlCeConnection connection = new SqlCeConnection("Data Source=|DataDirectory|\\Database1.sdf");
but I don't have result, I mean no delete no select no insert etc..
this my delete code:
SqlCeCommand cmd = new SqlCeCommand("delete from tab ", connection);
connection.Open();
cmd.ExecuteNonQuery();
connection.Close();

Database not being updated

This is my code:
conn = new SqlConnection("Server=(localdb)\\v11.0;Integrated Security=true;AttachDbFileName=|DataDirectory|\\Users.mdf;MultipleActiveResultSets=True;");
conn.Open();
SqlCommand comm = new SqlCommand("update users set surname='simpson' where id=1", conn);
int i = comm.ExecuteNonQuery();
MessageBox.Show(i + "");
comm = new SqlCommand("select surname from users where id=1", conn);
SqlDataReader reader = comm.ExecuteReader();
if (reader.Read())
MessageBox.Show(reader[0] + "");
conn.Close();
The ExecuteNonQuery returns 1 to show the database has been updated and the second query confirms it. But when I open the database in visual studio 2013, there are no changes, database still the same
YOu mean, when you stop the program and Visual Studio throws away the copy of the database and resets it to the empty one then the data is gone? Yes, that is true.
Maybe you need to change your connectionstring, or refresh the database.
Apparently the database had been set to copy to the output folder each time

Inserting data into sql server fails with no reason

I'm quite used to using c# with SQL server. I have no idea why a simple statement would fail to insert data. My code is as follows:
query = "INSERT INTO MCDPhoneNumber ([MCDID],[PhoneNumber])" +
"VALUES("+maxid+", '"+tel+"')";
SqlConnection conn = new SqlConnection("Data Source=source; ...");
SqlCommand newCommand = new SqlCommand(query, conn);
int success= myCommand.ExecuteNonQuery();
if (success!= 1)
{
MessageBox.Show("It didn't insert anything:" + query);
}
First of all let me tell that I know that I should use parameters for data and I initially did, but when it failed I tried a simple query and it still fails. For addition I can tell that I have a similar insert just before that one in another table and it works. What's funnier is that when I copy paste query to SQL Server Management Studio it works. It also doesn't report any error in process.
====================== Edit ===============================
If you wish to use old command object (i.e. myCommand) then use following code instead of creating a new command(newCommand)
myCommand.CommandText = query;
myCommand.CommandType = System.Data.CommandType.Text;
And then execute it
you are binding query with newCommand and executing myCommand.
====================== Edit ===============================
SqlCommand newCommand = new SqlCommand(query, conn);
here you have defined newCommand for SQLCOMMAND object
int success= myCommand.ExecuteNonQuery();
and you are accessing it as myCommand
And moreover i think you are not opening connection
First of all, you define your command as newCommand but you executing your myCommand.
You should always use parameterized queries for your sql queries. This kind of string concatenations are open for SQL Injection attacks.
query = "INSERT INTO MCDPhoneNumber (MCDID, PhoneNumber) VALUES(#maxid, #tel)";
using(SqlConnection conn = new SqlConnection("Data Source=source; Initial Catalog=base; Integrated Security = true"))
{
SqlCommand newCommand = new SqlCommand(query, conn);
conn.Open();
newCommand.Parameters.AddWithValue("#maxid", maxid);
newCommand.Parameters.AddWithValue("#tel", tel);
int success= newCommand.ExecuteNonQuery();
if (success != 1)
{
MessageBox.Show("It didn't insert shit:" + query);
}
}
And please be more polite about your error messages :)

Categories