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
}
}
}
Related
I created the following code:
public static bool setHeadword(int id, string headword)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\\pms.mdf;Integrated Security=True";
conn.Open();
SqlCommand command = new SqlCommand("UPDATE headwords SET Headword = #headword WHERE Id = #id", conn);
command.Parameters.AddWithValue("#headword", headword);
command.Parameters.AddWithValue("#id", id);
int result = command.ExecuteNonQuery();
conn.Close();
return true;
}
But the code doesn't work because the value in the database doesn't change.
If I run the code manually in the database the change takes place. But it won't work with C#.
Also the result variable are holding the right number of affected rows (1 in this case).
I'm not sure I have to flush the changes or something else.
Thanks for your help and best regards
Franz
static void Update(int id, string headword)
{
try
{
//You should create connectionString with correct details otherwise fail connection
string connectionString =
"server=.;" +
"initial catalog=employee;" +
"user id=sa;" +
"password=123";
using (SqlConnection conn =
new SqlConnection(connectionString))
{
conn.Open();
using (SqlCommand cmd =
new SqlCommand("UPDATE headwords SET Headword=#headword" +
" WHERE Id=#Id", conn))
{
cmd.Parameters.AddWithValue("#Id", id);
cmd.Parameters.AddWithValue("#headword", headword);
int rows = cmd.ExecuteNonQuery();
}
}
}
catch (SqlException ex)
{
//Handle sql Exception
}
}
For reference, this page (add.ashx.cs), is an add page to a database.
What I'm trying to do is :
figure out how to execute string queryID, and then
store the results of queryID
I'm a bit new at this, but this is what I'm working with so far. Am I on the right path, and what should I change? I don't believe the code below includes storing the results, but just executing queryID.
// new query to get last ID value
// store the command.executeNonQuery results into a variable
string queryID = "SELECT TOP (1) IDENT_CURRENT('dbo.license_info') FROM dbo.license_info";
// first: look up how to execute queryID
// then: store results of query ^
// execute queryID? (section below)
SqlConnection sqlConnection1 = new SqlConnection(queryID);
SqlCommand cmd = new SqlCommand();
SqlDataReader reader;
cmd.CommandText = "Select * FROM queryID";
cmd.CommandType = CommandType.Text;
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
reader = cmd.ExecuteReader();
// data is accessible through the datareader object here
sqlConnection1.Close();
There are some things missmatched in your code sample. First queryID is your actual query. Second in SqlConnection you need to provide a connection string, that connects to your database (SQL Server, ACCESS, ...). A valid example could look like this:
// this is just a sample. You need to adjust it to your needs
string connectionStr = "Data Source=ServerName;Initial Catalog=DataBaseName;Integrated Security=SSPI;";
SqlConnection sqlConnection1 = new SqlConnection(connectionStr);
SqlCommand cmd = new SqlCommand(sqlConnection1 );
SqlDataReader reader;
cmd.CommandText = "SELECT TOP (1) IDENT_CURRENT('dbo.license_info') FROM dbo.license_info";
cmd.CommandType = CommandType.Text;
sqlConnection1.Open();
reader = cmd.ExecuteReader();
List<string> results = new List<string>();
if(reader.HasRows)
{
while(reader.Read())
{
results.Add(reader[0].ToString());
}
}
sqlConnection1.Close();
Another thing is, that you execute a reader but only select one single value. You can perfectly use ExecuteScalar for that:
// this is just a sample. You need to adjust it to your needs
string connectionStr = "Data Source=ServerName;Initial Catalog=DataBaseName;Integrated Security=SSPI;";
SqlConnection sqlConnection1 = new SqlConnection(connectionStr);
SqlCommand cmd = new SqlCommand(sqlConnection1 );
cmd.CommandText = "SELECT TOP (1) IDENT_CURRENT('dbo.license_info') FROM dbo.license_info";
cmd.CommandType = CommandType.Text;
sqlConnection1.Open();
string result = cmd.ExecuteScalar().ToString();
sqlConnection1.Close();
One last thing. You should use objects that implement IDisposable in a using block. This way the will be removed from memory when they are no longer needed:
// this is just a sample. You need to adjust it to your needs
string connectionStr = "Data Source=ServerName;Initial Catalog=DataBaseName;Integrated Security=SSPI;";
using(SqlConnection sqlConnection1 = new SqlConnection(connectionStr))
{
SqlCommand cmd = new SqlCommand(sqlConnection1 );
cmd.CommandText = "SELECT TOP (1) IDENT_CURRENT('dbo.license_info') FROM dbo.license_info";
cmd.CommandType = CommandType.Text;
sqlConnection1.Open();
string result = cmd.ExecuteScalar().ToString();
}
As part of an application that I am trying to develop is to update records according to the service type. Hence, the Status attribute is graded from 1 to 8 (In progress = 3 and Complete = 5). I made my code but it seems not working as I try to pass values and test update the current service type as the following:
IF progress then update to 4
IF Completed then update 6
class Program
{
static void Main(string[] args)
{
int Bend = 4;
int Complete = 6;
List<int> Status = new List<int>();
foreach (int i in Status)
{
if (i == 3)
{
SqlConnection con = new SqlConnection(#"Data Source=
(localdb)\Projects;Initial Catalog=FLS_DB;Integrated
Security=True;Connect Timeout=30;Encrypt=False;");
con.Open();
SqlCommand cmd = new SqlCommand("Update Calls set
Service =#Service", con);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#Service", Bend);
con.Open();
int rowsAffected = cmd.ExecuteNonQuery();
con.Close();
}
else if (i == 5)
{
SqlConnection con = new SqlConnection(#"Data Source=
(localdb)\Projects;Initial Catalog=FLS_DB;Integrated
Security=True;
Connect Timeout=30;Encrypt=False;");
con.Open();
SqlCommand cmd = new SqlCommand("Update Calls set
Service =#Service", con);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#Service", Complete);
con.Open();
int rowsAffected = cmd.ExecuteNonQuery();
con.Close();
}
}
}
}
Any help would be much appreciated!
Your code is missing a WHERE statement to update only the records that match the conditions i == 3 or i == 5, thus it seems that you don't need a loop.
You just sets Service column to the new values Bend and Complete for all records that contain the value 3 or 5 in the Service column
using(SqlConnection con = new SqlConnection(....))
using(SqlCommand cmd = con.CreateCommand())
{
con.Open();
// Sets to 4 all records with 3
cmd.CommandText = "Update Calls set Service=#Service WHERE Service=3"
cmd.Parameters.AddWithValue("#Service", Bend);
int rowsUpdatedToBend = cmd.ExecuteNonQuery();
// No need to recreate the command, just change the commandtext and
// the value of the parameter #service
cmd.CommandText = "Update Calls set Service=#Service WHERE Service=5"
cmd.Parameters["#Service"].Value = Complete
rowsUpdatedToComplete = cmd.ExecuteNonQuery();
MessageBox.Show("You have changed " + rowsUpdatedToBend + " rows to Bend state\r\n" +
"You have changed " + rowsUpdatedToComplete + " rows to Complete state");
}
Does your connection string correct?
You are opening the connection twice by if condition
Put a break point and check where the programm is going
Assuming the first point is correct; could you try something like this (code edited):
string commandText = "UPDATE Calls SET Service=Service + 1 WHERE Service = 3 OR Service = 5;";
string connectionString = #"Data Source=
(localdb)\Projects;Initial Catalog=FLS_DB;Integrated
Security=True;Connect Timeout=30;Encrypt=False;";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(commandText, connection);
try
{
connection.Open();
int rowsAffected = command.ExecuteNonQuery();
Console.WriteLine("RowsAffected: {0}", rowsAffected);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
I have a retrieve code of:
[WebMethod]
public List<Hawker> retrievehawker()
{
List<Hawker> retrievehawker = new List<Hawker>();
string qry = #"select hawkername, address, postal, xcoord, ycoord, popularity from uploadphoto";
SqlConnection conn = new SqlConnection(connString);
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = qry;
conn.Open();
SqlDataReader mySqlDataReader = cmd.ExecuteReader();
while (mySqlDataReader.Read())
{
Hawker retrieveHawker = new Hawker();
retrieveHawker.hawkername = Convert.ToString(mySqlDataReader["hawkername"]);
retrieveHawker.address = Convert.ToString(mySqlDataReader["address"]);
retrieveHawker.postal = Convert.ToString(mySqlDataReader["postal"]);
retrieveHawker.xcoord = Convert.ToDouble(mySqlDataReader["xcoord"]);
retrieveHawker.ycoord = Convert.ToDouble(mySqlDataReader["ycoord"]);
retrieveHawker.popularity = Convert.ToDouble(mySqlDataReader["popularity"]);
retrievehawker.Add(retrieveHawker);
}
mySqlDataReader.Close();
conn.Close();
return retrievehawker;
}
and a setpopularity of :
[WebMethod]
public int SetPopularity()
{
string qry = #"update uploadphoto set popularity=popularity+1";
SqlConnection conn = new SqlConnection(connString);
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = qry;
conn.Open();
int status = cmd.ExecuteNonQuery();
conn.Close();
return status;
}
How can I combine them together so that based on a selection of a place in the windows phone 7, of a button click, then it will trigger the setpopularity. Right now the code for set popularity is adding the whole column of +1 to popularity. Help please.
You need to pass to your SetPopularity method the primary key (or another unique value) of your photo table.
In that way you could change your sql command to update only the record required
[WebMethod]
public int SetPopularity(string hawkername)
{
string qry = #"update uploadphoto set popularity=popularity+1
WHERE hawkername=#hawk";
using(SqlConnection conn = new SqlConnection(connString))
using(SqlCommand cmd = new SqlCommand(qry, conn))
{
conn.Open();
cmd.Parameters.AddWithValue("#hawk", hawkername);
int status = cmd.ExecuteNonQuery();
return status;
}
}
The string passed to the method is your primary key (or an unique value better if indexed) and could be used in the WHERE clause.
Notice also the using statement around the disposable objects and the parameterized query approach to avoid Sql Injections and parsing problems.
I need to retrieve Ticket_Id from tbl_Ticket to pass into body section of sending email function..
Is the below code correct?
every times i get Ticket_Id 1..
public int select_TicketId(){
string strConn = System.Configuration.ConfigurationManager.ConnectionStrings["conString"].ConnectionString.ToString();
SqlConnection sqlCon = new SqlConnection(strConn);
string getId = ("select Ticket_Id from tbl_Ticket where Client_EmailAdd='" + objNewTic_BAL.email + "' ");
sqlCon.Open();
SqlCommand cmd1 = new SqlCommand(getId, sqlCon);
int i=cmd1.ExecuteNonQuery();
return i;
}
You are searching for ExecuteScalar which returns the first value.
using System.Configuration;
//
public int select_TicketId()
{
string strConn = ConfigurationManager.ConnectionStrings["conString"].ConnectionString.ToString();
SqlConnection sqlCon = new SqlConnection(strConn);
string getId = ("select TOP 1 Ticket_Id from tbl_Ticket where Client_EmailAdd='" + objNewTic_BAL.email + "' ");
sqlCon.Open();
SqlCommand cmd1 = new SqlCommand(getId, sqlCon);
return Convert.ToInt32(cmd1.ExecuteScalar());
}
Also use CommandProperties to set the where statement for better security, like below:
public int select_TicketId()
{
string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
int result = -1;
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
SqlCommand command = new SqlCommand();
command.Connection = connection;
command.CommandType = CommandType.Text;
command.CommandText = "select TOP 1 Ticket_Id from tbl_Ticket where Client_EmailAdd=#email";
command.Parameters.Add("#email", SqlDbType.Text).Value = objNewTic_BAL.email;
result = Convert.ToInt32(command.ExecuteScalar());
}
return result;
}
You should call int i=(int)cmd1.ExecuteScalar(); method
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executescalar.aspx
You're calling ExecuteNonQuery. But it's a query. This should have rung some warning bells :)
Try ExecuteScalar instead, and cast the result to int...
return (int) cmd1.ExecuteScalar();
Note that you should use using statements for the command and connection as well, so that both are closed appropriately.
And (I hadn't spotted this before) you should definitely use parameterized SQL instead of including a value directly into your SQL. Otherwise you're open to SQL Injection attacks...
So something like:
private const string FetchTicketIdSql =
"select Ticket_Id from tbl_Ticket where Client_EmailAdd = #Email";
public int FetchTicketId()
{
// No need for ToString call...
string connectionString =
ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
using (SqlCommand command = new SqlCommand(connection, FetchTicketIdSql))
{
command.Parameters.Add("#Email", SqlDbType.NVarChar).Value =
bjNewTic_BAL.email;
return (int) command.ExecuteScalar();
}
}
}
You should consider what you want to happen if there isn't exactly one result though...
Hiral,
ExecuteNonQuery in
int i=cmd1.ExecuteNonQuery();
will return number of records that satisfy your query. In this case it is 1 (or 0 if there are no emails)
Try using ExecuteReader instead.