I am making an application, and I added a local database in visual studio. It all works fine while logging into app using crediantials stored in the database. But while adding new records, the query runs with no error but data is not actually stored in data base. Every thing else is working fine, except for the data not being stored.
Here is my code:
SqlConnection con = new SqlConnection(#" Data Source = (LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security = True");
SqlCommand cmd = new SqlCommand("insert into users(username,password,phone,adress,father_name,email)VALUES('"+username.Text+ "','"+password.Text+ "','"+phone.Text+ "','"+adress.Text+ "','"+fathername.Text+ "','"+email.Text+"')",con);
try
{
con.Open();
cmd.ExecuteNonQuery();
MessageBox.Show(username.Text + " Has been Added");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
con.Close();
}
Related
I have a stored procedure in one of my Azure databases that links to external tables from another database.
If I run this stored procedure in the DB it runs fine, returning the data I expect. If I call the same stored procedure with the same input parameters from C# code, it is running, but returning null data at the points where the data is fetched from the external tables.
I have checked my user has permission to access the external tables...
Would anyone have any ideas what else I can check?
Thanks,
private void UpdateTABLEX(int ID)
{
string CSQuery = "EXEC [stg].[UpdateTableX_Proc] #ID";
using (SqlConnection cn = new SqlConnection(DB1))
{
try
{
cn.Open();
using (SqlCommand cmd = new SqlCommand(CSQuery, cn))
{
cmd.Parameters.AddWithValue("#ID", ID);
cmd.ExecuteNonQuery();
}
Refresh();
}
catch (Exception e)
{
Error error = new Error(e.ToString(), "TableX Issue");
error.LogError();
}
}
}
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);
}
I have written this query in c# , query syntax is OK, query is also receiving parameter values as I have checked using breakpoints and also same query is working in SQL server management studio, but in visual studio it does not gives any error but also does not delete item from table.
private void deleteItem(int itemId, int saleId)
{
SqlConnection conn = new SqlConnection(connString);
SqlCommand deleteItem = new SqlCommand(
"Delete FROM items_in_sales WHERE sale_id=#sale_id AND item_id=#item_id",
conn);
deleteItem.Parameters.AddWithValue("#sale_id", itemId);
deleteItem.Parameters.AddWithValue("#item_id", saleId);
try
{
conn.Open();
deleteItem.ExecuteNonQuery();
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
please help.
Fix your parameters they are wrong way around
deleteItem.Parameters.AddWithValue("#sale_id", itemId);
deleteItem.Parameters.AddWithValue("#item_id", saleId);
should be
deleteItem.Parameters.AddWithValue("#sale_id", saleId);
deleteItem.Parameters.AddWithValue("#item_id", itemId);
I found this article for the majority of the code here How to set SQL Server connection string?.
Here's what I have though:
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Data Source=(localdb)\\Instance;" +
"Initial Catalog=Database;" +
"User id=root;Password=pass;";
try
{
conn.Open();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
SqlCommand myCommand = new SqlCommand("INSERT INTO Database.dbo.Table" +
"VALUES ('stg', 'stg1', 'stg2', 'stg3');", conn);
try
{
conn.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
A lot of the previous code was giving me errors. At one point, I was getting an error that I couldn't connect to the instance. This was an issue with the '\'. It was recognizing it as an escape character, so I did double '\' to get rid of that, so I'm not getting that error anymore, so that shouldn't be the problem.
I was getting an error about the wrong username and password. I'm using SQL Server Authentication and the code I was previously using was specifying Windows authentication. I'm not getting that error anymore.
As of right now, the code executes all the way through with no errors. When I check on the database though (I'm using SQL Server Management Studio), nothing gets inserted into the table. I have ran the Insert statement directly and it works fine, so I'm not sure what the issue is here. Also, I'm using VS 2013.
You are not using SqlCommand.ExecuteNonQuery to use the insert-command at all. Therefore nothing is inserted.
SqlCommand myCommand = new SqlCommand("INSERT INTO Database.dbo.Table" +
"VALUES ('stg', 'stg1', 'stg2', 'stg3');", conn);
int inserted = myCommand.ExecuteNonQuery();
You should also use the using-statement to ensure that all unmanaged resources are disposed and the connection gets closed even on error. Then you don't need to use conn.Close explicitly.
You are not executing the query. Add this after creating the command object:
myCommand.ExecuteNonQuery();
Side note: You should rather have a try...catch around all the code, and use using blocks for the connection and command. That will ensure that the objects are closed and disposed properly whatever happens:
try {
using (SqlConnection conn = new SqlConnection()) {
conn.ConnectionString =
"Data Source=(localdb)\\Instance;" +
"Initial Catalog=Database;" +
"User id=root;" +
"Password=pass;";
conn.Open();
using (SqlCommand myCommand = new SqlCommand("INSERT INTO Database.dbo.Table" +
"VALUES ('stg', 'stg1', 'stg2', 'stg3');", conn)) {
myCommand.ExecuteNonQuery();
}
}
} catch (Exception ex) {
Console.WriteLine(ex.ToString());
}
Hi all I have an small application to add the expense of the day.
For this I am using SQL compact database (CE). While inserting the record into a table name Expenses I am getting error
The specified table does not exist. [Expenses]
Insertion code is
using (var con =new SqlCeConnection(#"Data Source=|DataDirectory|\Database\Acadamy.sdf;
Persist Security Info=False"))
{
con.Open();
try
{
var Cmd = new SqlCeCommand();
String sqlAddNew = #"INSERT INTO Expenses (name, amount,receipt,details)
Values(#name,#amount,#receipt,#details)";
Cmd = new SqlCeCommand(sqlAddNew, con);
Cmd.Parameters.Add("#name", SqlDbType.NVarChar).Value = txtName.Text;
Cmd.Parameters.Add("#amount", SqlDbType.NVarChar).Value = txtAmount.Text;
Cmd.Parameters.AddWithValue("#receipt", SqlDbType.NVarChar).Value = txtRecept.Text;
Cmd.Parameters.AddWithValue("#details", SqlDbType.NVarChar).Value = txtDetails.Text;
Cmd.ExecuteNonQuery();
}
catch (Exception exception)
{
txtAmount.Text = exception.ToString();
}
finally
{
if (con.State == ConnectionState.Open) con.Close();
}
}
}
I am not getting why this error occurring.
Acadamy.sdf structure is as below:
I am able to retrieve data from another table of the same database. What will be the problem?
Whenever I get an error about a table that does not exist I use the SQL Server Management Studio and check if the table really is missing or if I just have a typo in my query.
Unfortunately the current version of the Management Studio no longer supports SQL Server Compact Database and you will have to use the 2008 version. You can get it directly from Microsoft: SQL Server 2008 R2 Management Studio Express