private void button1_click(object sender, EventArgs e)
{
conn.Open();
if (textBox3.Text.Trim() == textBox4.Text.Trim() && IsValidEmail(textBox1.Text))
{
MySqlCommand comm = conn.CreateCommand();
comm.CommandText = "INSERT into users(userName, password, email) values(#user,#pass,#mail)";
MySqlTransaction tx = conn.BeginTransaction();
comm.Transaction = tx;
try
{
comm.Parameters.AddWithValue("#user", MySqlDbType.Text).Value = textBox2.Text;
comm.Parameters.AddWithValue("#pass", MySqlDbType.Text).Value = textBox3.Text;
comm.Parameters.AddWithValue("#mail", MySqlDbType.Text).Value = textBox1.Text;
comm.ExecuteNonQuery();
tx.Commit();
}
catch
{
MessageBox.Show("Error!");
}
finally
{
conn.Close();
}
}
}
I don't know what I do wrong here.
As per the Microsoft doc, the AddWithValue method require two parameters :
The parameter name, as you did
The value itself.
I also emphasize the #Fildor comment, for security and legal resons you should only store hashed passwords Here is a great article about how to do it.
And here, why you should do it
Related
I'm pretty sure that the Sql Syntax is right since it's a legit query.
However i've never stumbled on this issue before.
private void button1_Click(object sender, EventArgs e)
{
string ett = textBox1.Text;
if (ett == "")
{
MessageBox.Show("Du måste fylla i UID, vilket du finner i användarlistan.");
return;
}
try
{
if (connect.State == ConnectionState.Open)
{
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = connect;
cmd.CommandText = "DELETE FROM Users WHERE uid = #uid";
cmd.Parameters.AddWithValue("#uid", textBox1.Text);
MySqlDataReader accessed = cmd.ExecuteReader();
MessageBox.Show("Användaren borttagen.");
}
else
{
MessageBox.Show("Något gick tyvärr fel, kontakta systemadministratören.");
}
}
catch (Exception ex)
{
{ MessageBox.Show(ex.Message); }
}
}
The problem may be related to this:
{
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = connect;
cmd.CommandText = "DELETE FROM Users WHERE uid = #uid";
cmd.Parameters.AddWithValue("#uid", textBox1.Text);
MySqlDataReader accessed = cmd.ExecuteReader();
MessageBox.Show("Användaren borttagen.");
}
try
{
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = connect;
cmd.CommandType = CommandType.Text
cmd.CommandText = "DELETE FROM Users WHERE uid = #uid";
cmd.Parameters.AddWithValue("#uid", textBox1.Text);
cmd.ExecuteNonQuery
MessageBox.Show("Användaren borttagen.");
}
Now you've shown us your whole code in the comments, the problem is obvious.
You have written a method to initialise, set up and open your database connection; and this other method which runs on a button click, which uses it.
However, nowhere in your code do you call the method which initialises your database connection, therefore it is not set up when you try to use it - obvious really.
I can see you think you are checking to see if the connection is working by checking its State property, but calling any sort of method or property accessor on an uninitialised reference type won't work, you'll get the NullReferenceException you've been getting.
To fix, call the connection set up method from your button press, before trying to use the connection:
private void button1_Click(object sender, EventArgs e)
{
string ett = textBox1.Text;
if (ett == "")
{
MessageBox.Show("Du måste fylla i UID, vilket du finner i användarlistan.");
return;
}
try
{
db_connection(); //added this line
if (connect.State == ConnectionState.Open)
{
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = connect;
cmd.CommandText = "DELETE FROM Users WHERE uid = #uid";
cmd.Parameters.AddWithValue("#uid", textBox1.Text);
MySqlDataReader accessed = cmd.ExecuteReader();
MessageBox.Show("Användaren borttagen.");
}
else
{
MessageBox.Show("Något gick tyvärr fel, kontakta systemadministratören.");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
You have not defined the variable, "connect".
I want to change password that saved in db,but my code dose not work. what is wrong? I always see the last message:
unable to connect database
public partial class pws : System.Web.UI.Page
{
static string strcon = (System.Web.Configuration.WebConfigurationManager.ConnectionStrings["strcon"].ConnectionString);
protected void Page_Load(object sender, EventArgs e)
{
}
private void ShowPopUpMsg(string msg)
{
StringBuilder sb = new StringBuilder();
sb.Append("alert('");
sb.Append(msg.Replace("\n", "\\n").Replace("\r", "").Replace("'", "\\'"));
sb.Append("');");
ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "showalert", sb.ToString(), true);
}
protected void btnInsert_Click(object sender, EventArgs e)
{
try {
SqlConnection db = new SqlConnection(strcon);
db.Open();
string strId = string.Empty;
string strusername = string.Empty;
string OLdpassword = string.Empty;
SqlCommand cmd;
cmd = new SqlCommand("SELECT * FROM login WHERE login_username =#login_username ", db);
cmd.Parameters.AddWithValue("login_username", txtOldUsername.Text);
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
cmd.Dispose();
cmd = null;
db.Close();
db.Open();
SqlDataReader DR;
DR = cmd.ExecuteReader();
if (DR.Read())
{
strId = DR["login_id"].ToString();
strusername = DR["login_username"].ToString();
OLdpassword = DR["login_Password"].ToString();
}
db.Close();
if (OLdpassword == txtOldPass.Text)
{
db.Open();
string Command = "Update login Set login_Password= #login_Password WHERE login_username=#login_username";
SqlCommand cmdIns = new SqlCommand(Command, db);
cmdIns.Parameters.AddWithValue("#login_Password ", txtNewPass.Text);
cmdIns.Parameters.AddWithValue("#login_username ", txtOldUsername.Text);
cmdIns.ExecuteNonQuery();
cmdIns.Parameters.Clear();
cmdIns.Dispose();
cmdIns = null;
db.Close();
ShowPopUpMsg("successful");
}
else
{
ShowPopUpMsg(" old pass is not correct");
}
}
catch
{
ShowPopUpMsg("unable to connect database");
}
}
}
this part:
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
cmd.Dispose();
cmd = null;
db.Close();
db.Open();
SqlDataReader DR;
DR = cmd.ExecuteReader();
why do you execute a non query, which is a query (select * from ...)?
why do you dispose the SqlCommand object cmd and why do you reuse it after disposing?
why do you close and open the line below?
I would rewrite those lines it like this:
SqlDataReader DR = cmd.ExecuteReader();
I would recomment a using statement or closing the connection in a finally block:
SqlConnection db = new SqlConnection(strcon);
try{
db.Open();
//.... the rest
}
catch(Exception ex)
{
ShowPopUpMsg("unable to connect database: " + ex.Message);
}
finally
{
db.Close();
}
and another thing: I would use the primary key in the update statement. where id = login_id instead of the username. unless the username is set to "unique"
Check if you can connect to the database using your credentials and database management tool (I assume you you use MS SQL Server so use MS SQL Server Management Studio)
Check if the format of your connection string is correct. You can use this website http://www.connectionstrings.com/ to do it.
I hope this will help you.
Try to step through the code and find where the exception occures, and look at the details of the exception.
My guess is that there are something wrong with you connection string (strcon).
protected void btnUpload_Click(object sender, EventArgs e)
{
if (FileUpload1.PostedFile != null)
{
string FileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
//Save files to disk
FileUpload1.SaveAs(Server.MapPath("" + FileName));
//Add Entry to DataBase
String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
OleDbConnection con = new OleDbConnection(strConnString);
string strQuery = "INSERT INTO image([FileName],[FilePath],[AlbumName]) Values(#FN, #FP, #AN)";
OleDbCommand cmd = new OleDbCommand(strQuery);
cmd.Parameters.AddWithValue("#FN", FileName);
cmd.Parameters.AddWithValue("#FP", "images/" + FileName);
cmd.Parameters.AddWithValue("#AN", txtAlbumname.Text.ToString());
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
try
{
con.Open();
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
con.Close();
con.Dispose();
}
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
string var = DropDownList1.SelectedItem.ToString();
txtAlbumname.Text = var.ToString();
}
}
I Have tried almost everything , but this error keeps on coming.
I have put on the brackets aswell incase of reserved words but still this error is showing
The OLE DB .NET Provider does not support named parameters for passing parameters to an SQL statement or a stored procedure called by an OleDbCommand when CommandType is set to Text. In this case, the question mark (?) placeholder must be used. For example:
SELECT * FROM Customers WHERE CustomerID = ?
Therefore, the order in which OleDbParameter objects are added to the OleDbParameterCollection must directly correspond to the position of the question mark placeholder for the parameter in the command text.
For Example
OleDbCommand command = new OleDbCommand(queryString, connection);
command.CommandText =
"SELECT CustomerID, CompanyName FROM Customers WHERE Country = ? AND City = ?";
command.Parameters.Add(parameters);
for (int j=0; j<parameters.Length; j++)
{
command.Parameters.Add(parameters[j]) ;
}
for reference ..
MSDN
IMAGE is a reserved word in Access SQL so to use it as a table name you must also enclose it in square brackets:
string strQuery = "INSERT INTO [image] ([FileName], ...
I got a question. When I put this code
protected void Page_Load(object sender, EventArgs e)
{
string email = Membership.GetUser(User.Identity.Name).Email;
MembershipUser currentUser = Membership.GetUser();
string UserId = currentUser.ProviderUserKey.ToString();
**TextBox2.Text = email;
TextBox3.Text = UserId;**
}
My data will not be saved to the database.
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Connection"].ConnectionString);
SqlCommand cmd = new SqlCommand("UPDATE aspnet_Membership SET Email = #email WHERE UserId = #id1", conn);
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#email", TextBox2.Text);
cmd.Parameters.AddWithValue("#id1", TextBox3.Text);
try
{
conn.Open();
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
throw ex;
}
finally
{
conn.Close();
}
But when I removed
**TextBox2.Text = email;
TextBox3.Text = UserId;**
The data will be saved into database using above code. Can someone tell me why? Thanks in advance.
Given you never execute the command I can't explain it.
Add
cmd.ExecuteNonQuery();
To the end of your click method
Because you are setting the values in your page load event, they are overwriting the changed values in the controls when your button on postback. Wrap your page load code with a
if (!Page.IsPostback)
{
string email = Membership.GetUser(User.Identity.Name).Email;
MembershipUser currentUser = Membership.GetUser();
string UserId = currentUser.ProviderUserKey.ToString();
TextBox2.Text = email;
TextBox3.Text = UserId;
}
You are never executing your SQL so I'm very surprised that your DB is updating at all.
Take a look at the ExecuteNonQuery method. With your current query you are creating a SQLCommand and then never running the SQL.
Try the following
cmd.Connection = conn;
cmd.Connection.Open()
after you assign it and then
cmd.ExecuteNonQuery();
I have some trouble to update my sql server 2005 database when i use parameters.Here you can see the code that normally has to work.I precise that i already make others treatments such as insert into and it worked perfectly.
myCommand.Parameters.AddWithValue("#Pk", this.pk);
myCommand.Parameters.AddWithValue("#Titre", this.titre);
myCommand.CommandText = "Update Action set titre=#Titre where pk=#Pk";
//Execute la commande
myCommand.ExecuteNonQuery();
EDIT:When i use hard code such as:
myCommand.CommandText = "Update Action set titre='title' where pk=#Pk";
it works...
I don't know where you went wrong this is the working code for me
string strCon = #"Data Source=SYSTEM19\SQLEXPRESS;Initial Catalog=TransactionDB;Integrated Security=True";
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
SqlConnection cn = new SqlConnection(strCon);
SqlCommand cmd = new SqlCommand("select * from tblTransaction1", cn);
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
DataSet ds = new DataSet();
da.Fill(ds);
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
txtName.Text = ds.Tables[0].Rows[i]["FirstName"].ToString();
txtName1.Text = ds.Tables[0].Rows[i]["LastName"].ToString();
}
}
}
Button click code
protected void btnInsert_Click(object sender, EventArgs e)
{
SqlConnection cn = new SqlConnection(strCon);
obj1.FirstName = txtName.Text;
obj1.LastName = txtName1.Text;
if (obj1.upDate(cn))
{
}
}
Sample class code file
private bool m_flag = false;
private string strFirstName;
private string strLastName;
public string FirstName
{
get { return strFirstName; }
set { strFirstName = value; }
}
public string LastName
{
get { return strLastName; }
set { strLastName = value; }
}
public bool upDate(SqlConnection con)
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
if (con.State != ConnectionState.Open)
{
con.Open();
}
try
{
cmd.Parameters.AddWithValue("#Fname", FirstName);
cmd.Parameters.AddWithValue("#Lname", LastName);
cmd.CommandText = "Update tblTransaction1 set LastName=#Lname where FirstName=#Fname";
if (cmd.ExecuteNonQuery() > 0)
{
m_flag = true;
}
}
catch
{
}
return m_flag;
}
Sample Images
I've seen weird results when you forget to include the "CommandType" parameter. Since you using inline SQL, it should be set to "CommandType.Text".
myCommand.Parameters.AddWithValue("#Pk", this.pk);
myCommand.Parameters.AddWithValue("#Titre", this.titre);
myCommand.CommandText = "Update Action set titre=#Titre where pk=#Pk";
// Added CommandType //
myCommand.CommandType = CommandType.Text;
//Execute la commande
myCommand.ExecuteNonQuery();
I have noticed that copying the entire code into a new project helps. I have ran into many times my code would work and then the next day would not, or would only work for someone else and not me. Usually this is due to the designer side of the project when adding and removing code from your project. Just because you delete specific code does not mean the program can update the entire class/project.
If you do :
Int32 rowsAffected = command.ExecuteNonQuery();
Console.WriteLine("RowsAffected: {0}", rowsAffected);
What does it say ?
Try also to prefix your Action table, with the schema name, for example :
myCommand.CommandText = "Update MySchema.Action set titre=#Titre where pk=#Pk";
Because sometimes it can depend on the schema and the user's rights to update this schema.
You could try this: instead of adding the parameters like that
myCommand.Parameters.AddWithValue("#Titre", this.titre);
you should add them with data type.
myCommand.Parameters.Add(new SqlParameter("#Titre", SqlDbType.VarChar, 50));
myCommand.Parameters["#Titre"].Value = this.titre;
That way, the final SQL will be Update Action set titre='titre' instead of Update Action set titre=title. Look that in the second statement titre is not inside quotes ''.
Try adding the parameters after declaring the command.
myCommand.CommandText = "Update Action set titre=#Titre where pk=#Pk";
myCommand.Parameters.AddWithValue("#Pk", this.pk);
myCommand.Parameters.AddWithValue("#Titre", this.titre);
//Execute la commande
myCommand.ExecuteNonQuery();
I found something similar (not identical) here: http://forums.asp.net/t/1249831.aspx/1