signup data failed in asp.net using mysql database - mysql

i try to build signup code using asp.net and mysql
code is
protected void Button2_Click(object sender, EventArgs e)
{
try
{
string MyConnection2 = "Server=xxx; Port=3306 ; Uid=xxx; pwd=xxx;Database=maintainance";
string Query = "INSERT INTO `login`(`UName`, `UPasword`,`UserTypeID`,`Email`)VALUES('" + this.TextBox1.Text + "','" + this.TextBox2.Text + this.DropDownList1.SelectedValue +this.TextBox3.Text+ "');";
MySqlConnection MyConn2 = new MySqlConnection(MyConnection2);
MySqlCommand MyCommand2 = new MySqlCommand(Query, MyConn2);
MySqlDataReader MyReader2;
MyConn2.Open();
MyReader2 = MyCommand2.ExecuteReader();
Label3.Text = ("Your Data saved successfully");
while (MyReader2.Read())
{
}
MyConn2.Close();
}
catch
{
Label3.Text = ("Data saved failed");
}
}
but it shows me Data saved failed ... where is the error and how i correct this?

You have to pass value according to column before VALUES
string Query = "INSERT INTO `login`(`UName`, `UPasword`,`UserTypeID`,`Email`) VALUES ('" + this.TextBox1.Text + "','" + this.TextBox2.Text+"', '"+this.DropDownList1.SelectedValue+"' ,'"+this.TextBox3.Text+ "');";

Related

get image from Api to xamarin

I want get image from API to XAMARIN I have API connected to MYSQL if I try get image he give me nothing that is the code.
API
[HttpGet]
public string Plan(string Code, string Company, string Centrale, string Zone)
{
object imag = null;
DataSet ds = new DataSet();
try
{
MySqlConnection con = new MySqlConnection(connectionDB.ConnectionString);
MySqlCommand cmd = new MySqlCommand("select imag from photo inner join taskhis on photo.company = taskhis.company and " +
" photo.zone = taskhis.zone where taskhis.codes ='" + Code + "' and taskhis.company ='" + Company + "' " +
"and taskhis.centrale = '" + Centrale + "' and taskhis.zone = '" + Zone + "' and dates ='" + DateTime.Now.ToString("yyyy/MM/dd") + "' group by taskhis.zone", con);
con.Open();
MySqlDataReader dr = cmd.ExecuteReader();
if(dr.Read())
{
imag = dr[0];
}
//MySqlDataAdapter da = new MySqlDataAdapter(cmd);
//da.Fill(ds);
dr.Close();
con.Close();
}
catch (Exception ex)
{
}
return imag.ToString() ;
}
connection method
string MainUri = "http://192.168.1.25:5873/api/C1NET/";
public async Task<string> GetRequest(string uri)
{
string Tache = "";
var client = new RestClient(MainUri);
var request = new RestRequest(uri);
var response = client.Execute(request);
return response.Content;
}
MainPage
string[] item = plan.urTask.Split(';');
VPNConnector VP = new VPNConnector();
string Result = VP.GetRequest("Plan?Code=" + item[4]+ "&Company="+item[0]+ "&Centrale="+item[1]+ "&Zone="+item[2]).Result;
byte[] image = Encoding.ASCII.GetBytes(Result);
MemoryStream ms = new MemoryStream(image);
IMAGES.Source = ImageSource.FromStream(() => ms);
please if someone can help me to fix my code that can be great thank you

Displaying values from table in VS2013 forms

I have created a login form, which checks database for username and password you provided, and if username exists logs you in and transfer you to next form which says: "Welcome 'username' " . Now, I want to show other info from another table about the person who loggs in that are recorded in the database. Here is my code, been struggling with it, don't know what to change to make it work, I'm getting errors for cmd and reader saying that they don't exist in the current context.
private void PopulateFields()
{
string conString = (#"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\slame\OneDrive\Dokumenti\relacijska_baza_podataka.mdf;Integrated Security=True;Connect Timeout=30;");
SqlConnection con = new SqlConnection(conString);
string selectSql = "select * from Pending_Tasks";
SqlCommand com = new SqlCommand ("Select * From student where username='" + textBox3.Text + "' and Password ='" + textBox4.Text + "'", con);
try
{
con.Open();
using (SqlDataReader read = cmd.ExecuteReader())
{
while(reader.Read())
{
textBox3.Text = (read["username"].ToString());
textBox4.Text = (read["password"].ToString());
}
}
}
finally
{
con.Close();
}

How do I close mysql connection after if-statement if it is true?

I'm new to ASP.NET and I'm stuck on this problem. I get the error:
Error:System.InvalidOperationException: The connection was not closed. The connection's current state is open. at System.Data.ProviderBase.DbConnectionInternal.
Here is my code, the error points towards 'while' statement. I've tried number of things but nothing worked. I know that I need to close connection when if-statement is true but don't know how. Can anyone help me on this? Thanks.
protected void loadtour()
{
try
{
conn.Open();
string strSelect = "Select * From Agents where Agent_ID='" + AgID.Text + "'";
SqlCommand cmd = new SqlCommand(strSelect, conn);
SqlDataReader myReader = cmd.ExecuteReader();
while (myReader.Read())
{
if (myReader["Agent_Status"].ToString() == "On Tour")
{
Label1.Text = "Assigned Tour Details:";
try
{
conn.Open();
SqlDataAdapter da = new SqlDataAdapter("SELECT PackageInfo.pkg_Name, PackageInfo.pkg_Type, PackageInfo.pkg_Status, Packages.pkg_Country, Packages.pkg_Start, Packages.pkg_End, PackageInfo.Agent_ID, PackageInfo.Agent_Name FROM PackageInfo INNER JOIN Packages ON PackageInfo.pkg_ID = Packages.pkg_ID WHERE(PackageInfo.Agent_ID = '" + AgID.Text + "')", conn);
DataTable ds = new DataTable();
da.Fill(ds);
gv1.DataSource = ds;
gv1.DataBind();
}
catch (Exception ex)
{
Response.Write("Error:" + ex.ToString());
}
conn.Close();
}
else
{
Label1.Text = "No Tour Assigned Yet!";
}
myReader.Close();
conn.Close();
}
}
catch (Exception ex)
{
Response.Write("Error:" + ex.ToString());
}
}
using (var connection = new SqlConnection(connectionString))
{
connection.Open();
//Do stuff with the connection
}
Wrap your connection in a using block. This guarantees it always gets closed.

Do not insert duplicate values into mysql

I want to insert users in mysql without duplicate values at the field "User" .how to show a message to the user when he writes a "User" already exist in the table before he complete the rest of the fields and before he clicks on the button Login?
public void Registrar() throws SQLException {
Connection con = null;
ResultSet rs = null;
Statement st = null;
String user;
String pass;
String pass2;
String email;
String country;
user = jTextField1.getText();
pass = jPasswordField1.getText();
pass2 = jPasswordField2.getText();
email = jTextField2.getText();
country = jComboBox1.getSelectedItem().toString();
if (user.isEmpty()) {
jLabel8.setText("Please enter an Username");
} else if (pass.isEmpty()) {
jLabel8.setText("Please enter an password");
} else if (pass2.isEmpty()) {
jLabel8.setText("please you must confirm your password");
} else if (!pass2.equals(pass)) {
jLabel8.setText("passwords do not match");
} else if (email.isEmpty()) {
jLabel8.setText("Please enter an valid email");
} else if (country.equals("Choose your country")) {
jLabel8.setText("Please choose a Country");
} else {
String sql = "INSERT INTO usuarios(User,Pass,Email,Country) "
+ "VALUES('" + user + "','" + pass + "','" + email + "','" + country + "')";
try{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost/whichmovie", "Asis", "dekrayat24");
System.out.println("Conectado a la base de datos SQLite");
PreparedStatement pstm = con.prepareStatement(sql);
pstm.execute();
pstm.close();
JOptionPane.showMessageDialog(rootPane, "Congratulations you have created your account");
dispose();
Login l = new Login(null, rootPaneCheckingEnabled);
l.setVisible(true);
} catch (Exception e) {
JOptionPane.showMessageDialog(rootPane, "An error has occurred ,please try later");
}
}
}

Syntax error (missing operator) in query expression 'System.Byte[]'

Hi i was using stored procedure in SQL Server to pass parameters to the query ,
but now I'm changing my database to ms access and it's my first time to deal with.
how can i pass byte[] to sql query ?
bacause i got this error
Syntax error (missing operator) in query expression 'System.Byte[]'.
this is my code
public static int EditWhois(object ID,object Image, object Ranswer, object Fanswer1, object Fanswer2, object Fanswer3)
{
int result = 0;
String sql = "UPDATE Whois SET [Image]="+#Image+", Ranswer=" + Ranswer + ", Fanswer1=" + Fanswer1 + ",Fanswer2=" + Fanswer2 + ",Fanswer3=" + Fanswer3 + " WHERE ID=" + ID;
System.Windows.Forms.MessageBox.Show(sql);
cmd = new OleDbCommand(sql, con);
//cmd.Parameters.AddWithValue("#ID", ID);
//cmd.Parameters.AddWithValue("#Image", Image);
//cmd.Parameters.AddWithValue("#Ranswer", Ranswer);
//cmd.Parameters.AddWithValue("#Fanswer1", Fanswer1);
//cmd.Parameters.AddWithValue("#Fanswer2", Fanswer2);
//cmd.Parameters.AddWithValue("#Fanswer3", Fanswer3);
if (con.State != ConnectionState.Open)
{
con.Open();
result = cmd.ExecuteNonQuery();
con.Close();
}
return result;
}
Use # parameter substitution. Also as #BoltClock says, change you method signature.
public static int EditWhois(object ID,object Image, object Ranswer,
object Fanswer1, object Fanswer2, object Fanswer3)
{
int result = 0;
String sql = "UPDATE Whois SET [Image]=#Image, Ranswer=#Ranswer, " +
"Fanswer1=#Fanswer1, Fanswer2=#Fanswer2, Fanswer3=#Fanswer3 " +
"WHERE ID=#ID";
cmd = new OleDbCommand(sql, con);
cmd.Parameters.AddWithValue("#ID", ID);
cmd.Parameters.AddWithValue("#Image", Image);
cmd.Parameters.AddWithValue("#Ranswer", Ranswer);
cmd.Parameters.AddWithValue("#Fanswer1", Fanswer1);
cmd.Parameters.AddWithValue("#Fanswer2", Fanswer2);
cmd.Parameters.AddWithValue("#Fanswer3", Fanswer3);
if (con.State != ConnectionState.Open)
{
con.Open();
result = cmd.ExecuteNonQuery();
con.Close();
}
return result;
}
result is still 0;
i know the problem where it was .
if the connection is closed the query will be executed successfully , but if it is opend it will not be executed due to this condition .
if (con.State != ConnectionState.Open)
{
con.Open();
result = cmd.ExecuteNonQuery();
con.Close();
}
it must be
if (con.State != ConnectionState.Open)
{
con.Open();
}
result = cmd.ExecuteNonQuery();
con.Close();
thanks all .