sqlite insert with c# - 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);
}

Related

C# delete query not working

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

Stored Procedure returns a 0 only when on the server - not when run locally

I have the following code to return an id number from a database. It works fine when I run it locally, but when I put the files onto the server, while it does log the data into the DB, but it only returns a 0 and not the ID number.
HHID is an ID that autoincrements when I log the info to the DB.
SqlConnection conn = new SqlConnection("DB connection stuff");
SqlCommand cmd = conn.CreateCommand();
SqlDataReader reader;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "insert_workshop_requests";
cmd.Parameters.AddWithValue("#HHID", 1);
cmd.Parameters.AddWithValue("#username", usernameData.Text);
cmd.Parameters.AddWithValue("#name", nameData.Text);
cmd.Parameters.AddWithValue("#email", emailData.Text);
cmd.Parameters["#HHID"].Direction = System.Data.ParameterDirection.Output;
try
{
conn.Open();
reader = cmd.ExecuteReader();
HHID = System.Convert.ToInt32(cmd.Parameters["#HHID"].Value);
}
catch (Exception exc)
{
}
finally
{
if (conn.State != ConnectionState.Closed)
conn.Close();
}
This is driving me crazy! Hoping someone can help, because while I've found loads of useful articles about SP that store a 0 rather than an ID, the issues are always when running locally as well. Mine working locally is making it very difficult to debug!
Thanks!
You are using ExecuteReader for something that is not a SELECT. This has an interesting side effect on return parameters. Until you close the reader the values inside parameters of Direction = Output are not available.
SQL OUTPUT Stored Procedures not working with ExecuteReader
So you could close the reader, but really you should use ExecuteNonQuery for INSERT/UPDATE/DELETE queries
conn.Open();
reader = cmd.ExecuteReader();
reader.Close();
HHID = System.Convert.ToInt32(cmd.Parameters["#HHID"].Value);
or better
conn.Open();
int records = cmd.ExecuteNonQuery();
HHID = System.Convert.ToInt32(cmd.Parameters["#HHID"].Value);
as far as i can understand, you are trying to return the id of the last entry,
for that you can use this and bind the result to a variable and return it
SELECT SCOPE_IDENTITY()
i hope this will work out

How To create a stored procedure for SQL Server from C# code?

I am trying to create a stored procedure in SQL server from a C# winforms application.
This is the function I have so far.
public void CreateStoredProcedure(string SPname)
{
try
{
string query = "CREATE PROCEDURE " + SPname + " AS SELECT * FROM People WHERE Address='Mumbai'";
connection.Open();
var command = new SqlCommand();
command.CommandType = CommandType.Text;
command.CommandText = "EXEC " + query;
command.ExecuteNonQuery();
}
finally
{
connection.Close();
}
}
Am I doing this right? I get an error message every time I try to achieve this.
Hey thanks a lot guys!! Its working now..
This is the code that finally did it..
public void CreateStoredProcedure(string SPname)
{
try
{
string query = "CREATE PROCEDURE " + SPname + " AS SELECT * FROM People WHERE Address='Mumbai'";
connection.Open();
var command = new SqlCommand();
command.Connection = connection;
command.CommandText = query;
command.ExecuteNonQuery();
var adapter = new SqlDataAdapter(command);
adapter.Fill(dt);
dgv.DataSource = dt;
}
finally
{
connection.Close();
}
}
much appreciated! :)
You do not need EXEC when creating a stored procedure
and you need an active connection
You can try:
command.CommandType = CommandType.StoredProcedure;
Initialize connection property of your command:
command.Connection = connection;
Alternatively, you can create a Stored Procedure using Common Language Run-time integration in stead of doing it on the fly.
How to: Create and Run a SQL Server Stored Procedure by using Common Language Run-time Integration
Deploy CLR Stored Procedure to database
In your attempt above the code will only be able to run as a once off as it contains a CREATE command. It must then change to ALTER there after or you need to drop it every time and re-created. this would not be the best practice but just keep in mind.
You need to define a connection object and link it with the command object
CommandObject.Connection= ConnectionObject;
Also the CommandType.Text is by default.
You could also check if you connection is open using
if(ConnectionObject.State== ConncetionState.Closed)
{
ConnectionObject.Open();
}
If it is closed, you will need an active Open connection to pass a query.

how to delete data in Sql Server 2012 using c#?

i want to delete data in my database and using this code but its now working
private static void DeletePreviousRecord()
{
string connectionString = "Data Source=ABDULLAH\\ABDULLAHZAFAR;Initial Catalog=FoodHunt;Integrated Security=True";
using (SqlConnection con = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand("Delete From RestaurantsMenu", con))
{
try
{
cmd.CommandType = CommandType.StoredProcedure;
con.Open();
var result = cmd.ExecuteNonQuery();
con.Close();
}
catch (Exception ex)
{ }
}
}
}
i tried this but this is not working, how can i do that, any suggestion?
Setting the CommandType to StoredProcedure when you clearly use a sql text directly cannot do any good at your code.
Remove that line because the default is CommandType.Text (and this is correct for your command)
But as stated in the comment above.
If you catch the exception, at least write in some log or display at
video what the error message is
If you don't add a WHERE clause at your sql statement, you delete
everything in the table (Probably you are lucky that this code has
not worked)
Looking at your comment below, if you want to delete every record (and reset the Identity column if any) a faster approach is
using (SqlCommand cmd = new SqlCommand("TRUNCATE TABLE RestaurantsMenu", con))
For a quick reading about the difference between TRUNCATE and DELETE look at this article

C# OleDB SQL Insert Command

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.

Categories