The title is probably confusing, but basically i want to do something along the lines of this,
string sql = "select dataset1 from dbo.ste where project = 'whatever' and date = '11/30/10'";
SqlConnection con = new SqlConnection("Data Source= Watchmen ;Initial Catalog= doeLegalTrending;Integrated Security= SSPI");
con.Open();
SqlCommand cmd = new SqlCommand(sql, con);
cmd.ExecuteNonQuery();
con.Close();
if(cmd "is not null")
{
//do this string
}
else
{
//do this one
}
obviously cmd "is not null") is not real, but i think you guys might get the point.
I don't understand why everyone is trying to use ExecuteNonQuery or ExecuteScalar when the query in the question is a SELECT statement. If it was a stored procedure call that took care of the logic of INSERT versus UPDATE based on the existence of a value, the ExecuteScalar would make sense because you can return whatever single value you want from a stored procedure.
However, given the structure of the question, I'm leaning towards this as the answer.
// Automatically dispose the connection when done
using(SqlConnection connection = new SqlConnection(sqlConnection.ConnectionString)) {
try {
connection.Open();
// query to check whether value exists
string sql = #"SELECT dataset1
FROM dbo.ste
WHERE project = 'whatever'
AND date = '2010-11-30'";
// create the command object
using(SqlCommand command = new SqlCommand(sql, connection)) {
using(SqlDataReader reader = command.ExecuteReader()) {
// if the result set is not NULL
if(reader.HasRows) {
// update the existing value + the value from the text file
}
else {
// insert a value from a text file
}
}
}
}
finally {
// always close connection when done
if(connection.State != ConnectionState.Closed) {
connection.Close();
}
}
}
You can change the query to use WHERE EXISTS if you don't want to stream back full matches, but from the sounds of it, you would only have at most 1 match anyways.
If you want to check if there is any matching records, you can count them:
string sql = "select count(*) from dbo.ste where project = 'whatever' and date = '11/30/10'";
To get the result you use the ExecuteScalar method:
int cnt = Convert.ToInt32(cmd.ExecuteScalar());
It looks like you want to do var result = cmd.ExecuteScalar(); and then compare if (result == DBNull.Value).
ExecuteNonQuery returns the number of rows affected (if certain options are not selected) as an integer. So, you can either verify the count is equal to (or greater than) some success condition or execute scalar and return a value from your query to indicate success.
Try this:
string sql = "select COUNT(dataset1) from dbo.ste where project = 'whatever' and date = '11/30/10'";
SqlConnection con = new SqlConnection("Data Source= Watchmen ;Initial Catalog= doeLegalTrending;Integrated Security= SSPI");
con.Open();
SqlCommand cmd = new SqlCommand(sql, con);
int count = Convert.ToInt32(cmd.ExecuteScalar());
con.Close();
if(count != 0)
{
//do this string
}
else
{
//do this one
}
Related
I'm trying to delete record from data base MSSQL by entering the ID and hit delete btn. i didn't get any error and it give recorded deleted successful but once i check database i see the record doesn't deleted
protected void btnDelete_Click(object sender, EventArgs e)
{
try
{
if (txtImgID.Text == "")
{
Response.Write("Enter Image Id To Delete");
}
else
{
SqlCommand cmd = new SqlCommand();
SqlConnection con = new SqlConnection();
con = new SqlConnection(ConfigurationManager.ConnectionStrings["GMSConnectionString"].ConnectionString);
con.Open();
cmd = new SqlCommand("delete from certf where id=" + txtImgID.Text + "", con);
lblsubmitt.Text = "Data Deleted Sucessfully";
}
}
catch (Exception)
{
lblsubmitt.Text = "You haven't Submited any data";
}
}
var idToDelete = int.Parse(txtImgID.Text); // this is not necessary if the data type in the DB is actually a string
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["GMSConnectionString"].ConnectionString))
using (SqlCommand cmd = new SqlCommand("DELETE FROM [certf] WHERE id = #id", con))
{
// I am assuming that id is an integer but if it is a varchar/string then use the line below this one
// cmd.Parameters.Add("#id", SqlDbType.VarChar, 100).Value = txtImgID.Text;
cmd.Parameters.Add("#id", SqlDbType.Int32).Value = idToDelete;
cmd.ExecuteNonQuery();
}
You need to call ExecuteNonQuery which executes the query against the database.
Always use parameters instead of string concatenation in your queries. It guards against sql injection and ensures you never has issues with strings that contain escape characters.
I did not include any error handling or return messages but do note that you are throwing away all the good stuff in your excetion handler's catch block, you will never know why a query failed after this has executed.
I have tried this code in C#, and it's not working - I can't get an input id, every time I run it, the value of id is 0.
SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=sms;Persist Security Info=True;User ID=boy;Password=coco");
int id;
con.Open();
string sql = "select * from Staff_Management where Emp_Name = '"+sName+"'; ";
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataReader read = cmd.ExecuteReader();
if (read.Read())
{
id = read.GetInt32(0);
TM_AC_SelectId.Text = id.ToString();
}
else
{
MessageBox.Show("Error 009 ");
}
con.Close();
You should try to follow the accepted best practices for ADO.NET programming:
use parameters for your query - always - no exceptions
use the using(...) { .... } construct to ensure proper and quick disposal of your resources
select really only those columns that you need - don't just use SELECT * out of lazyness - specify your columns that you really need!
Change your code to this:
// define connection string (typically loaded from config) and query as strings
string connString = "Data Source=.;Initial Catalog=sms;Persist Security Info=True;User ID=boy;Password=coco";
string query = "SELECT id FROM dbo.Staff_Management WHERE Emp_Name = #EmpName;";
// define SQL connection and command in "using" blocks
using (SqlConnection con = new SqlConnection(connString))
using (SqlCommand cmd = new SqlCommand(query, con))
{
// set the parameter value
cmd.Parameter.Add("#EmpName", SqlDbType.VarChar, 100).Value = sName;
// open connection, execute scalar, close connection
con.Open();
object result = cmd.ExecuteScalar();
con.Close();
int id;
if(result != null)
{
if (int.TryParse(result.ToString(), out id)
{
// do whatever when the "id" is properly found
}
}
}
I'm beginner in SQL and C#. My question is: how do I check whether a row in the table exists or not? Here is my code that I am currently using:
var conn = new SqlConnection(#"Data Source");
conn.Open();
var cmd = new SqlCommand("INSERT INTO Results (PlayerName) VALUES (#PlayerName) " , conn);
cmd.Parameters.Add("#PlayerName",_playerName);
cmd.ExecuteNonQuery();
conn.Close();
I want to check if the player name exists or not, and if not, then add it to the table.
You can check it with Select statement first and then insert it if it is not exist.
Also use using statement to dispose your connection and commands automatically instead of calling Close method manually.
using(var conn = new SqlConnection(yourConnectionString))
using(var cmd = conn.CreateCommand())
{
cmd.CommandText = "Select Count(*) From Results Where PlayerName = #playerName";
cmd.Parameters.Add("#playerName", _playerName);
con.Open();
int count = (int)cmd.ExecuteScalar();
if(count == 0)
{
// It means it does not exist.
cmd.CommandText = "INSERT INTO Results(PlayerName) VALUES (#playerName)";
cmd.ExecuteNonQuery();
}
}
if not exists(select null from Results where PlayerName=#PlayerName) begin INSERT INTO Results (PlayerName) VALUES (#PlayerName) end
I have got the input to work but now I need to add to the original number every time I input to the database but I do not know how to do that, any help would be appreciated :)
String myConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=E:/coursework/Databases/runner database.accdb;"; // location of the database
OleDbConnection myConnection = new OleDbConnection(myConnectionString); // To create the database connection
OleDbCommand myCommand = new OleDbCommand(); // Use the connection for the command
myCommand.Connection = myConnection;
try
{
myConnection.Open(); // Opens the database connection
string query = "insert into tblTrainingInformation ([Username],[Calories Burnt]) values('"+GlobalUsername.username+"','" + this.txtCaloriesBurntRun.Text + "')";
OleDbCommand createCommand = new OleDbCommand(query, myConnection);
createCommand.ExecuteNonQuery();
MessageBox.Show("Your running information has been saved");
myConnection.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
If you want to UPDATE an existing record adding a new value to your field or INSERT a new record if it is not present you need to know if your database already contains the Username.
So you need to run a SELECT query before and then decide if you need an UPDATE or an INSERT
(Access doesn't have some kind of UPSERT statement like MySql or Sql Server)
String myConnectionString = ".....";
string querySel = #"SELECT [Username],[Calories Burnt]
FROM tblTrainingInformation
WHERE [Username] = #uname";
using(OleDbConnection myConnection = new OleDbConnection(myConnectionString))
using(OleDbCommand myCommand = new OleDbCommand(querySel, myConnection))
{
myConnection.Open();
myCommand.Parameters.AddWithValue("#uname", GlobalUsername.username);
using(OleDbDataReader reader = myCommand.ExecuteReader())
{
int calories = 0;
string query = "";
if(reader.Read())
{
// The record exists, read the calories and add the new value
// then execute the UPDATE
calories = Convert.ToInt32(reader["Calories Burnt"]);
calories += Convert.ToInt32(this.txtCaloriesBurntRun.Text);
query = #"UPDATE tblTrainingInformation
SET [Calories Burnt] = #cal
WHERE [Username] = #uname";
}
else
{
// Record doesn't exist, INSERT the new data
calories = Convert.ToInt32(this.txtCaloriesBurntRun.Text);
query = #"INSERT INTO tblTrainingInformation
([Calories Burnt],[Username])
VALUES(#cal, #uname)";
}
reader.Close();
myCommand.Parameters.Clear();
myCommand.Parameters.AddWithValue("#cal", calories);
myCommand.Parameters.AddWithValue("#uname", GlobalUsername.username);
myCommand.ExecuteNonQuery();
MessageBox.Show("Your running information has been saved");
}
}
I have made a couple of assumption here.
First I assume that UserName is the primary key in this table so you can retrieve the record using the WHERE on username value.
The second assumption is the type of the field Calories Burnt.
It should be a numeric field and, to simplify the example, I have considered it to be an integer.
These assumptions should be checked and fixed if they are not true.
Said that, notice the use of the Using Statement to correctly dispose the connection, command and reader. The removing of string concatenation from your queries is another important point. You should ALWAYS use the parameter collection to avoid Sql Injection (albeit improbable with Access) and error in parsing your values.
A final note on the order of the parameters. OleDb wants the parameter in the exact order in which the parameter placeholders appear in the query text so I have reversed the order of the INSERT to be compatible with the UPDATE command
I've been writing a lot of web services with SQL inserts based on a stored procedure, and I haven't really worked with any SELECTS.
The one SELECT I have in mind is very simple.
SELECT COUNT(AD_SID) As ReturnCount FROM AD_Authorization
WHERE AD_SID = #userSID
However, I can't figure out based on my current INSERT code how to make that into a SELECT and return the value of ReturnCount... Can you help? Here is my INSERT code:
string ConnString = "Data Source=Removed";
string SqlString = "spInsertProgress";
using (OleDbConnection conn = new OleDbConnection(ConnString))
{
using (OleDbCommand cmd = new OleDbCommand(SqlString, conn))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("attachment_guid", smGuid.ToString());
cmd.Parameters.AddWithValue("attachment_percentcomplete", fileProgress);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
}
Here is where you are going wrong:
cmd.ExecuteNonQuery();
You are executing a query.
You need to ExecuteReader or ExecuteScalar instead. ExecuteReader is used for a result set (several rows/columns), ExecuteScalar when the query returns a single result (it returns object, so the result needs to be cast to the correct type).
var result = (int)cmd.ExecuteScalar();
The results variable will now hold a OledbDataReader or a value with the results of the SELECT. You can iterate over the results (for a reader), or the scalar value (for a scalar).
Since you are only after a single value, you can use cmd.ExecuteScalar();
A complete example is as follows:
string ConnString = "Data Source=Removed";
string userSid = "SomeSid";
string SqlString = "SELECT COUNT(AD_SID) As ReturnCount FROM AD_Authorization WHERE AD_SID = #userSID;";
int returnCount = 0;
using (OleDbConnection conn = new OleDbConnection(ConnString))
{
using (OleDbCommand cmd = new OleDbCommand(SqlString, conn))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#userSID", userSid);
conn.Open();
returnCount = Convert.ToInt32(cmd.ExecuteScalar());
}
}
If you wanted to return MULTIPLE rows, you can use the ExecuteReader() method. This returns an IDataReader via which you can enumerate the result set row by row.
You need to use ExecuteScalar instead of ExecuteNonQuery:
String query = "SELECT COUNT(AD_SID) As ReturnCount FROM AD_Authorization WHERE AD_SID = #userSID ";
using (OleDbConnection conn = new OleDbConnection(ConnString)) {
using (OleDbCommand cmd = new OleDbCommand(query, conn))
{
cmd.Parameters.AddWithValue("userSID", userSID.ToString());
conn.Open();
int returnCount = (Int32) cmd.ExecuteScalar();
conn.Close();
}
}
cmd.executescalar will return a single value, such as your count.
You would use cmd.executereader when you are returning a list of records