When I try to select values from a local database it executes without any issue. But when I try to insert and delete it's executing the query but it's not affecting any rows.
This is the code I'm using to delete row from my local database:
SqlCeConnection sqlConnection1 = new SqlCeConnection();
sqlConnection1.ConnectionString = "Data Source = Database1.sdf";
SqlCeCommand cmd = sqlConnection1.CreateCommand();
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = "DELETE FROM table1 WHERE slno=2";
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
cmd.Prepare();
int aff=cmd.ExecuteNonQuery();//here its returning '0'
MessageBox.Show(aff.ToString());
sqlConnection1.Dispose();
sqlConnection1.Close();
It is possible that the delete won't affect any rows.
As an aside, I would advise using the using statement in your code:
using (SqlCeConnection conn = new SqlCeConnection("Data Source = Database1.sdf"))
using (SqlCeCommand comm = new SqlCeCommand("DELETE FROM table1 WHERE slno = 2", conn))
{
conn.Open();
comm.CommandType = CommandType.Text;
comm.ExecuteNonQuery();
}
This will handle disposal of relevant objects for you.
Assuming that the SQL is relevant to your database and that you have successfully connected using the connection string beforehand, then the above could will perform a delete action against your database.
Related
I am trying to update username from MVC .Net C# after connecting Postgres SQL.
I am able to establish the connection and if I run select command I am able to get the result.
But when I am trying to update record no error comes but updated count comes 0. Record available in database.
Can you please suggest what could be the reason.
using (NpgsqlConnection con = new NpgsqlConnection(connectionString))
{
string query = string.Format("UPDATE um_user SET um_user_name='{0}' WHERE um_user_name='{1}'", updatedUser, userNameToBeUpdated);
con.Open();
NpgsqlCommand comn = new NpgsqlCommand(query, con);
comn.Connection = con;
updatedRows = comn.ExecuteNonQuery();
comn.Dispose();
con.Close();
}
I have added using parameter as well with the following code but still getting 0 updtaed rows.
using (NpgsqlConnection connection = new NpgsqlConnection())
{
connection.ConnectionString = connectionString;
connection.Open();
NpgsqlCommand cmd = new NpgsqlCommand();
cmd.Connection = connection;
cmd.CommandText = "update um_user set um_user_name=#newName where um_user_name=#oldName";
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add(new NpgsqlParameter("#newName", updatedUser));
cmd.Parameters.Add(new NpgsqlParameter("#oldName", userNameToBeUpdated));
updatedRows = cmd.ExecuteNonQuery();
cmd.Dispose();
connection.Close();
}
Below is a snapshot of my code. I am trying to access the only column in the customer table and place the values into a textbox on the form. I keep getting the error with my code "InvalidOperationException was unhandled" at the line declaring dr as a OleDbDataReader object.
What do I have wrong with the below code that would be giving me this error?
Should I do a list to pick out the text I want from the database?
How can I return the column values from access into a list in C# so that I can search the list for a particular value?
string strsql = "Select * from Customer";
OleDbCommand cmd = new OleDbCommand();
cmd.CommandText = strsql;
conn.Open();
OleDbDataReader dr = cmd.ExecuteReader();
while(dr.Read())
{
textBox1.Text += dr["Customer"].ToString();
}
conn.Close();
A command carries the info to be executed, a connection carries the info to reach the database server. The two objects should be linked together to produce any result. You miss that line
OleDbCommand cmd = new OleDbCommand();
cmd.CommandText = strsql;
cmd.Connection = conn; // <= here
conn.Open();
Remember also that disposable objects like a command, a reader and a connection should be disposed immediately after usage. For this pattern exists the using statement
So you should write
string cmdText = "Select * from Customer";
using(OleDbConnection conn = new OleDbConnection(.....constring...))
using(OleDbCommand cmd = new OleDbCommand(cmdText, conn))
{
conn.Open();
using(OleDbDataReader reader = cmd.ExecuteReader())
{
while(reader.Read())
.....
}
}
Here is some sample code.
try
{
using (OleDbConnection myConnection = new OleDbConnection())//make use of the using statement
{
myConnection.ConnectionString = myConnectionString;
myConnection.Open();//Open your connection
OleDbCommand cmdNotReturned = myConnection.CreateCommand();//Create a command
cmdNotReturned.CommandText = "someQuery";
OleDbDataReader readerNotReturned = cmdNotReturned.ExecuteReader(CommandBehavior.CloseConnection);
// close conn after complete
// Load the result into a DataTable
if (readerNotReturned != null) someDataTable.Load(readerNotReturned);
}
}
After that you have a Datatable containing your data. Ofcourse you can afterwards search for records in the Datatable any way you like.
I cannot get my program to clear an SQL database on opening. I have went through debugging and there are no errors in the code for deleting, but it just doesn't do it
string delete = "Delete from Trivia";
con.Open();
SqlCommand comm = new SqlCommand(delete, con);
con.Close();
You're not actually executing the command. You might also consider a using statement. That will automatically dispose of the connection properly, even if an error occurs:
using (SqlConnection con = new SqlConnection(connectionString))
{
con.Open();
SqlCommand comm = new SqlCommand("delete from Trivia", con);
comm.ExecuteNonQuery();
}
I am currently trying to populate a listview with some data I have pulled from my database table; but not sure where to start; I have tried the following:
lstData.DataSource = conn;
lstData.DataBind();
But that causes an error:
"Data source is an invalid type. It must be either an IListSource,
IEnumerable, or IDataSource. MVC"
Am I using the correct query strings in order to populate my listview?
Thanks,
Callum
C# Code:
string ssConnectionString = "Server connection";
SqlConnection conn = new SqlConnection(ssConnectionString);
conn.Open();
SqlCommand command = conn.CreateCommand();
command.CommandText = "SELECT Category FROM [dbo].[Category] WHERE CategoryID = '16'";
command.ExecuteNonQuery();
string com = command.ExecuteScalar().ToString();
lblSQL.Text = com;
conn.Close();
Using your code as a base to start from you may want to try the following: I assume your connection in "Server connection" is a place holder for a real connection string and you know what should go there.
string ssConnectionString = "Server connection";
SqlConnection conn = new SqlConnection(ssConnectionString);
conn.Open();
SqlCommand command = conn.CreateCommand();
command.CommandText = "SELECT Category FROM [dbo].[Category] WHERE CategoryID = '16'";
SqlDataAdapter da = new SqlDataAdapter(command);
DataTable dataTable;
da.Fill(dataTable);
lstData.DataSource = dataTable;
lstData.DataBind();
conn.Close();
I am using SQl CLR for parsing some table column. I want to execute the queries also in C# user defined function. Can somebody give an example to execute select and insert queries in the function?
Thank you in advance.
SqlConnection objSqlConn;
string connString = string.Empty;
connString = "Data Source=(local);Initial Catalog=DB;User ID=uname;pwd=pass;Password=pass";
objSqlConn = new SqlConnection(connString);
objSqlConn.Open();
string query = "Select count(*) FROM [DB].[dbo].[TableName]";
SqlCommand cmdTotalCount = new SqlCommand(query, objSqlConn);
cmdTotalCount.CommandTimeout = 0;
string TotalCountValue = cmdTotalCount.ExecuteScalar().ToString();
return TotalCountValue;
In CLR, you can use existing connection to run queries.
Simple, returning data to client:
var cmd = new SqlCommand("select * from [table]");
SqlContext.Pipe.ExecuteAndSend(cmd);
Returning data via SqlDataReader:
var con = new SqlConnection("context connection=true"); // using existing CLR context connection
var cmd = new SqlCommand("select * from table", con);
con.Open();
var rdr = cmd.ExecuteReader();
SqlContext.Pipe.Send(rdr);
rdr.Close();
con.Close();
Running other commands:
var con = new SqlConnection("context connection=true"); // using existing CLR context connection
var cmd = new SqlCommand("insert into [table] values ('ahoj')", con);
con.Open();
var rsa = cmd.ExecuteNonQuery();
con.Close();
Once you switch to C# you execute queries like you'd normally do from your application (using ADO.NET's SqlConnection and SqlDataReader, using LINQ to SQL or using your custom build data layer).
To connect with the database you have to mention the database username and password in the connection string of your web.config file.