I am unable to find the problem here but this does not work! Any help will be appreciated.
It is a bool thing BTW.Every time i debug, it logs an error as follows
Invalid attempt to read when no data is present
ICCqueueLabelDropDownList.Items.Clear();
string queryString = "(SELECT [name] FROM [asterisk].[dbo].[sip_friends] where name = '" + phoneNumberDropDownList.SelectedItem + "');";
SqlConnection conn = new SqlConnection(connectionString);
SqlCommand selectCmd = new SqlCommand(queryString, conn);
SqlDataReader myReader = null;
bool value = false;
try
{
conn.Open();
myReader = selectCmd.ExecuteReader();
//myReader.Read();
if (myReader["name"].ToString() != "" ) /* ( myReader["name"].ToString() != "" */
{
myReader.Read();
value = true;
}
}
catch (Exception ex)
{
//ErrorLabel.Text = ex.Message;
hiba.Visible = true;
hiba.Text = ex.Message + "\n Check Insert Call User Device ÁLERT!";
}
myReader.Close();
conn.Close();
return (value);
}
#andrew, kindly go through below code and let me know is it working for you or not?
string connectionString = "[YOUR_CONNECTION_STRING]";
ICCqueueLabelDropDownList.Items.Clear();
string queryString = "(SELECT [name] FROM [asterisk].[dbo].[sip_friends] where name = '" + phoneNumberDropDownList.SelectedItem + "');";
SqlConnection conn = new SqlConnection(connectionString);
SqlCommand selectCmd = new SqlCommand(queryString, conn);
SqlDataReader myReader = null;
bool value = false;
try
{
conn.Open();
myReader = selectCmd.ExecuteReader();
if (myReader.Read())
{
if (myReader["name"].ToString() != "")
{
value = true;
}
}
}
catch (Exception ex)
{
}
myReader.Close();
conn.Close();
return (value);
}
Related
Trying to update the first name of the student there is a textbox "FirstNameTextbox" information was loaded to it from the DB, when I change the information in the textbox and try to write the changes it read only the original data.So if it loaded "Craig" as the first name from the DB, i would edit and put "Chris" in the textbox, what happens is that Craig is written to the DB and not "Chris"
int stuID = getSqlStuID(IDNUMLabel.Text);
SqlConnection conn = new SqlConnection(GetConnectionString());
string sqlUpdateStudent = "Update tblStudent set fname = #fname where stuID = #stuID";
SqlCommand cmd = new SqlCommand(sqlUpdateStudent, conn);
conn.Open();
cmd.Parameters.AddWithValue("#stuID", stuID);
cmd.Parameters.AddWithValue("#fname", FirstNameTextbox.Text);
cmd.ExecuteNonQuery();
ErrorMessage.Text = "Success";
protected void Page_Load(object sender, EventArgs e)
{
if (Session["User"] != null)
{
IDNUMLabel.Text = Session["User"].ToString();
getStuData(Session["User"].ToString());
}
else
{
Response.Redirect("../Login/Login.aspx");
}
}
private void getStuData(string id)
{
SqlConnection conn = new SqlConnection(GetConnectionString());
string sql = "Select fname, sname From tblStudent Where idnumber = '" + id + "' ";
SqlCommand cmd = new SqlCommand(sql, conn);
try
{
conn.Open();
SqlDataReader selectedRecord = cmd.ExecuteReader();
cmd.CommandType = CommandType.Text;
while (selectedRecord.Read())
{
FirstNameTextbox.Text = selectedRecord["fname"].ToString();
LastNameTextbox.Text = selectedRecord["sname"].ToString();
}
selectedRecord.Close();
}
catch (System.Data.SqlClient.SqlException ex)
{
//id = 0;
//string msg = "Error reading Student ID";
//msg += ex.Message;
//throw new Exception(msg);
}
catch (Exception ex)
{
}
finally
{
conn.Close();
}
}
At what point do you make the actual update? After a button was pressed, after the value was entered on the textbox...? You're missing the method in which the code that handles the update is placed...
Maybe this could help: How to display data from database into textbox, and update it
I created a folder on a webform in visual studio for images and titled as (Invoices), I want to save the root of images in MySql database and display the images on a panel one the webpage. The image has been saved on the folder but not on database.
The Codes I have tried
protected void Page_Load(object sender, EventArgs e)
{
string connection = "server=localhost; userid= ; password= ; database=admindb; allowuservariables=True";
MySqlConnection cn = new MySqlConnection(connection);
try
{
string sqlcmd = "SELECT PicAddress FROM InvoicesFP WHERE InvoicesFP_ID=#InvoicesFP_ID";
cn.Open();
MySqlCommand cmd = new MySqlCommand(sqlcmd, cn);
cmd.CommandType = CommandType.Text;
MySqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
string url = rdr["PicAddress"].ToString();
Image1.ImageUrl = url;
}
}
catch (Exception ex)
{
throw ex;
}
cn.Close();
}
protected void Button1_Click(object sender, EventArgs e)
{
#region fileupload
var FileExtension = Path.GetExtension(FileUpload1.PostedFile.FileName).Substring(1);
string SaveLocation = Server.MapPath("Invoices\\") + Guid.NewGuid().ToString("N") + FileExtension;
MySqlConnection connection = new MySqlConnection("server=localhost; userid=root; password=admin1234; database=admindb; allowuservariables=True");
MySqlCommand cmd = new MySqlCommand();
cmd.CommandText = "insert into invoicesfp (PicAddress), VALUES (#PicAddress)";
cmd.CommandType = CommandType.Text;
cmd.Connection = connection;
cmd.Parameters.AddWithValue("PicAddress", Server.MapPath("~/Invoices"));
cmd.Connection.Open();
cmd.BeginExecuteNonQuery();
cmd.Connection.Close();
try
{
FileUpload1.PostedFile.SaveAs(SaveLocation);
}
catch (Exception ex)
{
if (ex is ArgumentNullException || ex is NullReferenceException)
{
throw ex;
}
}
string PicAddress = "~/Invoices/" + SaveLocation;
}
#endregion
}
Update
Try this Code first, using this sample you do not need to use Rename Method And whatever its Extension is, it is supported:
#region fileupload
var FileExtension = Path.GetExtension(FileUpload1.PostedFile.FileName).Substring(1);
string SaveLocation = Server.MapPath("Invoices\\") + Guid.NewGuid().ToString("N") + "." + FileExtension;
try
{
FileUpload1.PostedFile.SaveAs(SaveLocation);
}
catch (Exception ex)
{
if (ex is ArgumentNullException || ex is NullReferenceException)
{
throw ex;
}
}
string PicAddress = "~/Invoices/" + SaveLocation;
#endregion
MySqlConnection connection = new MySqlConnection("server=localhost; userid=root; password=admin1234; database=admindb; allowuservariables=True");
MySqlCommand cmd = new MySqlCommand();
cmd.CommandText = "INSERT INTO InvoicesFP (PicAddress) VALUES (#PicAddress)";
cmd.CommandType = CommandType.Text;
cmd.Connection = connection;
cmd.Parameters.AddWithValue("PicAddress", "PicAddress");
cmd.Connection.Open();
cmd.ExecuteNonQuery();
cmd.Connection.Close();
then in your page_load you can call the Select Query to get the Address out database and pass it over to control e.g:
const string DB_CONN_STR = "Server=etc;Uid=etc;Pwd=etc;Database=etc;";
MySqlConnection cn = new MySqlConnection(DB_CONN_STR);
try {
string sqlCmd = "SELECT PicAddress FROM [YourTable] where Id == PicAddress id";
cn.Open(); // have to explicitly open connection (fetches from pool)
MySqlCommand cmd = new MySqlCommand(sqlCmd, cn);
cmd.CommandType = CommandType.Text;
MySqlDataReader rdr = cmd.ExecuteReader();
while(rdr.Read())
{
string url = rdr["Name of the Field Assuming PicAddress"].ToString();
Image1.ImageUrl = url;
}
}
catch(Exception ex)
{
throw ex;
}
Thats All - Happy Coding
I have a dropdownlist item named IsAuthor. It do not fill my textboxes by retrieving value from tblnewgroup table. Where is the problem I can not understand and it do not show any error please help me
protected void lstAuthor_SelectedIndexChanged(object sender, EventArgs e)
{
string selectSQL;
selectSQL = "SELECT * FROM tblnewgroup ";
selectSQL += "WHERE Groupno='" + lstAuthor.SelectedItem.Value + "'";
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(selectSQL, con);
SqlDataReader reader;
try
{
con.Open();
reader = cmd.ExecuteReader();
reader.Read();
txtGn.Text = reader["Groupno"].ToString();
txtgname.Text=reader["Groupname"].ToString();
txtsl.Text=reader["Slno"].ToString();
txtsn.Text = reader["Subname"].ToString();
reader.Close();
lblResults.Text = "";
}
catch (Exception err)
{
lblResults.Text = "Error getting author. ";
lblResults.Text += err.Message;
}
finally
{
con.Close();
}
}
I filled my drop down list by these codes..
private void FillAuthorList()
{
lstAuthor.Items.Clear();
string selectSQL = "SELECT Groupname, Groupno FROM tblnewgroup";
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(selectSQL, con);
SqlDataReader reader;
try
{
con.Open();
reader = cmd.ExecuteReader();
while (reader.Read())
{
ListItem newItem = new ListItem();
newItem.Text = reader["Groupname"].ToString();
newItem.Value = reader["Groupno"].ToString();
lstAuthor.Items.Add(newItem);
}
reader.Close();
}
catch (Exception err)
{
lblResults.Text = "Error reading list of names. ";
lblResults.Text += err.Message;
}
finally
{
con.Close();
}
}
Problem : you are assigning single quotes to number feild Groupno.
Solution : you need to assign single quotes to VARCHAR Types only.
Suggestion: you are just assigning the values from SqlDataReader object without checking for rows.if the rows are not found then it will throw the Exeption. So i would suggest to Ceck the SqlDataReader object for any rows before assigning the values to TextBox Controls.
Try This:
protected void lstAuthor_SelectedIndexChanged(object sender, EventArgs e)
{
string selectSQL;
selectSQL = "SELECT * FROM tblnewgroup ";
selectSQL += "WHERE Groupno=" + lstAuthor.SelectedValue;
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(selectSQL, con);
SqlDataReader reader;
try
{
con.Open();
reader = cmd.ExecuteReader();
if(reader.Read())
{
txtGn.Text = reader["Groupno"].ToString();
txtgname.Text=reader["Groupname"].ToString();
txtsl.Text=reader["Slno"].ToString();
txtsn.Text = reader["Subname"].ToString();
lblResults.Text = "Data Updated Successfully!";
}
else
{
lblResults.Text = "No Records found!";
}
reader.Close();
}
catch (Exception err)
{
lblResults.Text = "Error getting author. ";
lblResults.Text += err.Message;
}
finally
{
con.Close();
}
}
It looks like you're selecting on a number field, but treating it like a text field. Modify your query to remove the single quotes:
selectSQL = "SELECT * FROM tblnewgroup ";
selectSQL += "WHERE Groupno=" + lstAuthor.SelectedItem.Value;
Also check the return value of reader.read() to see if there are any records:
using(var reader = cmd.ExecuteReader())
{
if(reader.Read())
{
txtGn.Text = reader["Groupno"].ToString();
txtgname.Text=reader["Groupname"].ToString();
txtsl.Text=reader["Slno"].ToString();
txtsn.Text = reader["Subname"].ToString();
}
else
{
lblResults.Text = "Author not found";
}
}
Note that I've put the reader in a using block to ensure it is closed, even if an exception occurs.
I assume SqlDataReader.Read method returns boolean value and you can use it like;
while(reader.Read())
{
txtGn.Text = reader["Groupno"].ToString();
txtgname.Text=reader["Groupname"].ToString();
txtsl.Text=reader["Slno"].ToString();
txtsn.Text = reader["Subname"].ToString();
}
Also I suspect lstAuthor.SelectedItem.Value is a number instead of a string. You might need to use it without using "".
Also using parameterized queries always a good choice.
selectSQL = "SELECT * FROM tblnewgroup WHERE Groupno = #Groupno";
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(selectSQL, con);
cmd.Parameters.AddWithValue("#Groupno", lstAuthor.SelectedItem.Value);
....
Use following:
while (reader.Read())
{
txtGn.Text = reader["Groupno"].ToString();
txtgname.Text=reader["Groupname"].ToString();
txtsl.Text=reader["Slno"].ToString();
txtsn.Text = reader["Subname"].ToString();
}
I am trying to delete a row in my users_stocks table.
I use this code:
public bool removeStock(string user_name,string stock_symbol)
{
user_name = user_name.Trim();
stock_symbol = stock_symbol.Trim();
string statement = "DELETE FROM " + "users_stocks" + " WHERE user_name = '" + user_name + "'" + " AND " + "stock_symbol = " + "'" + stock_symbol + "'" ;
SqlCommand cmdnon = new SqlCommand(statement, connection);
try
{
connection.Open();
int num = cmdnon.ExecuteNonQuery();
connection.Close();
return true;
}
catch (SqlException ex)
{
Console.WriteLine(ex.ToString());
connection.Close();
return false;
}
}
There is a row with this data, but the query wont erase it.
What am i missing?
Use parametrized query to avoid Sql Injection Attacks and quoting problems
Not to mention that a parametrized query could be stored by the optimization engine of SqlServer and reused more quickly. An hand made query will be reevaluated every time you send to the database-
public bool removeStock(string user_name,string stock_symbol)
{
user_name = user_name.Trim();
stock_symbol = stock_symbol.Trim();
string statement = "DELETE FROM users_stocks " +
"WHERE user_name = #name AND stock_symbol = #stock" ;
SqlCommand cmdnon = new SqlCommand(statement, connection);
try
{
cmdnon.Parameters.AddWithValue("#name", user_name);
cmdnon.Parameters.AddWithValue("#stock", stock_symbol);
connection.Open();
int num = cmdnon.ExecuteNonQuery();
connection.Close();
return true;
}
catch (SqlException ex)
{
Console.WriteLine(ex.ToString());
connection.Close();
return false;
}
}
As Luis Quijada mentioned above use parameters, they are much safer. In the code below just change the YOUR_CONNECTION_STRING value and the SqlDbType to the ones matching in your DB.
public bool removeStock(string user_name, string stock_symbol)
{
using(SqlConnection connection = new SqlConnection("YOUR_CONNECTION_STRING"))
{
using(SqlCommand command = new SqlCommand())
{
try
{
command.Connection = connection;
command.CommandText = "DELETE FROM user_stocks WHERE user_name=#USERNAME AND stock_symbol=#STOCKSYMBOL";
command.Parameters.Add("#USERNAME", SqlDbType.VarChar).Value = user_name.Trim();
command.Parameters.Add("#STOCKSYMBOL", SqlDbType.VarChar).Value = stock_symbol.Trim();
connection.Open();
int i = command.ExecuteNonQuery();
if (i == 0)
return false;
return true;
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
connection.Close();
return false;
}
finally
{
connection.Close();
}
}
}
}
Try this code :
public bool removeStock(string user_name,string stock_symbol)
{
user_name = user_name.Trim();
stock_symbol = stock_symbol.Trim();
string statement = "DELETE FROM users_stocks
WHERE user_name = '" + user_name + "'
AND stock_symbol = '" + stock_symbol + "'" ;
SqlCommand cmdnon = new SqlCommand(statement, connection);
try
{
connection.Open();
int num = cmdnon.ExecuteNonQuery();
connection.Close();
return true;
}
catch (SqlException ex)
{
Console.WriteLine(ex.ToString());
connection.Close();
return false;
}
}
Change in query
when i specify values in my update query the query works fine and the database gets updated, but when i use parameters in my query the database does not update
here is the code i have written
try
{
OdbcConnection MyConnection = new OdbcConnection(ConfigurationManager.ConnectionStrings["myconn"].ConnectionString);
MyConnection.Open();
String MyString = "UPDATE orddetpabak SET jud1=#jud1,jud2=#jud2,jud3=#jud3,adv=#adv where fil_no=#fil_no AND orderdate=#orderdate";
OdbcCommand MyCmd = new OdbcCommand(MyString, MyConnection);
String j1=DropDownList4.SelectedValue;
String j2=DropDownList5.SelectedValue;
String j3=DropDownList6.SelectedValue;
String j4=TextBox4.Text;
String j5 = HiddenField1.Value;
String j6 = TextBox3.Text;
MyCmd.Parameters.AddWithValue("#jud1",j1);
MyCmd.Parameters.AddWithValue("#jud2",j2);
MyCmd.Parameters.AddWithValue("#jud3",j3);
MyCmd.Parameters.AddWithValue("#adv",j4);
MyCmd.Parameters.AddWithValue("#fil_no",j5);
MyCmd.Parameters.AddWithValue("#orderdate",j6);
Response.Write(DropDownList4.SelectedValue);
Response.Write(" " + DropDownList5.SelectedValue);
Response.Write(" " + DropDownList6.SelectedValue);
Response.Write(" " + TextBox4.Text);
Response.Write(" " + HiddenField1.Value);
Response.Write(" " + TextBox3.Text);
MyCmd.ExecuteNonQuery();
//MyConnection.Close();
}
catch(Exception epp)
{
Response.Write(epp);
}
Please Help
As far as I know you cannot use named parameters in MySQL. If you change your string to be
String MyString = "UPDATE orddetpabak SET jud1=?,jud2=?,jud3=?,adv=?
where fil_no=? AND orderdate=?";
and your parameters as:
MyCmd.Parameters.AddWithValue("",j1);
MyCmd.Parameters.AddWithValue("",j2);
MyCmd.Parameters.AddWithValue("",j3);
MyCmd.Parameters.AddWithValue("",j4);
MyCmd.Parameters.AddWithValue("",j5);
MyCmd.Parameters.AddWithValue("",j6);
Hope this helps.
It can be like the following: (I'm using the ADO.NET driver for MySQL version 6.3.7.0, latest one had some issues).
public bool UpdateCustomerIAR(IAR oIAR)
{
bool bRetVal = false;
try
{
MySqlConnection dbConnection = new MySqlConnection(APPSConn.ConnectionString);
MySqlCommand dbCommand = dbConnection.CreateCommand();
string szSQL = string.Empty;
szSQL = "UPDATE schema.table_name SET field_name_one=?field_name_one";
szSQL += " WHERE field_name_two=?field_name_two";
using (MySql.Data.MySqlClient.MySqlConnection conn = new
MySql.Data.MySqlClient.MySqlConnection(APPSConn.ConnectionString))
{
MySql.Data.MySqlClient.MySqlCommand cmd = new MySql.Data.MySqlClient.MySqlCommand();
cmd.Connection = conn;
cmd.CommandText = szSQL;
cmd.Parameters.AddWithValue("?field_name_one", oIAR.Title);
cmd.Parameters.AddWithValue("?field_name_two", oIAR.IARID.ToString());
conn.Open();
cmd.ExecuteNonQuery();
bRetVal = true;
}
return bRetVal;
}
catch (MySqlException ex)
{
ErrorHandler(ex.ToString());
return bRetVal;
}
catch (Exception ex)
{
ErrorHandler(ex.ToString());
return bRetVal;
}
}