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");
}
}
}
Related
I need to query the database.
This query is working correctly, but I need to loop to read all data in the table.
I don't know how to put "do" or "while" in this query
[HttpPost]
public IActionResult SendMessage(string send_to, string message, string phone)
{
var email = HttpContext.Session.GetString("email");
MySqlDataReader reader;
try
{
cmdMySQL.Connection = conMySQL;
conMySQL.Open();
cmdMySQL.CommandText = "SELECT * FROM tbl_mensagens WHERE enviado = '" + 0 + "' AND email_usuario = '" + email + "' ";
reader = cmdMySQL.ExecuteReader();
while (reader.Read())
{
var codmsgx ="";
phone = "";
message = "";
codmsgx = reader[0].ToString();
phone = reader[4].ToString();
message = reader[5].ToString();
EnviarMensagem(send_to, message, phone, email, codmsgx);
AtualizarBd(send_to, message, phone, email, codmsgx);
}
reader.Close();
return View();
}
catch (Exception ex) { Debug.WriteLine(ex); return View(); }
finally
{
conMySQL.Close();
}
}
You're only getting one row because you're calling reader.Read(). Each time you call Read(), the reader advances to the next row and returns true; or, when the reader advances past the last row, it returns false.
Assume that you have a view model:
public class MensagensViewModel
{
public string Codmsgx { get; set; }
public string Phone { get; set; }
public string Message { get; set; }
}
To get the List<MensagensViewModel> data from tbl_mensagens table, you need to manually save the accessed data into mensagens shown as below code:
try
{
cmdMySQL.Connection = conMySQL;
cmdMySQL.CommandText = "SELECT * FROM tbl_mensagens WHERE enviado = '" + 0 + "' AND email_usuario = '" + email + "' ";
conMySQL.Open();
reader = cmdMySQL.ExecuteReader();
List<MensagensViewModel> mensagens = new List<MensagensViewModel>();//To save all retrieved data
while (reader.Read())
{
var mensagen = new MensagensViewModel()
{
Codmsgx = reader[0].ToString(),
Phone = reader[4].ToString(),
Message = reader[5].ToString()
};
mensagens.Add(mensagen);
//other logic
}
reader.Close();
return View();
}
catch (Exception ex) { Debug.WriteLine(ex); return View(); }
finally
{
conMySQL.Close();
}
So what i want to do is "Update the 'usertype' column in the 'user' table WHERE the email(/user) value is obtained from the textbox " below is my database connection code (which 100% works)
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import javax.swing.JOptionPane;
public class Database_link {
Connection connect = null;
Statement state = null;
public static Connection dbConnector()
{
try{
Class.forName("org.hsqldb.jdbcDriver");
Connection connect = DriverManager.getConnection("jdbc:hsqldb:file: // my DB path )
JOptionPane.showMessageDialog(null, "Connection Successful");
return connect;
}
catch (Exception e) {
JOptionPane.showMessageDialog(null, "Failed Connection");
return null;
}
}
}
Below is the sql statement code with the error "The operator & is undefined for the argument type(s) java.lang.String, java.lang.String"
JButton GrantButton = new JButton("Grant Seller Access");
GrantButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
String update_query = "UPDATE user SET usertype = 'seller' WHERE email = " & GrantField.getText()";"
//Here is where the error is stated on eclipse
PreparedStatement pSt = connect.prepareStatement(update_query);
pSt.setString(1, GrantField.getText());
pSt.execute();
JOptionPane.showMessageDialog(null,
"The Request has been approved");
} catch (Exception e) {
e.printStackTrace();
}
}
});
Sorry to have repeated the question
String update_query = "UPDATE user SET usertype = 'seller' WHERE email = " & GrantField.getText()";"
should be like
String update_query = "UPDATE user SET usertype = 'seller' WHERE email = ?"
String update_query = "UPDATE user SET usertype = 'seller' WHERE email = " & GrantField.getText()";"
Wrong syntax. That's why this error comes.
"The operator & is undefined for the argument type(s) java.lang.String, java.lang.String"
Correct syntax is -
String update_query = "UPDATE user SET usertype = 'seller' WHERE email = "+GrantField.getText();
But you have to use ? because it will get value from below line.
pSt.setString(1, GrantField.getText());
We use '+' operator for concatenate instead of & (ampersand) operator.
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+ "');";
How to connect infobright DB through perl ?
With DBD-mysql. Install it with
perl Makefile.PL --mysql_config=/usr/local/infobright-3.5.2-x86_64/bin/mysql_config
or similar.
You can connect to Infobright using any standard database connection that you'd use with MySQL. Daxim is correct -- DBD is one of the most common ways to connect to the database. In your DBD config, all you'd need to do is change the port number from 3306 (MysQL) to 5029 (Infobright). All the rest is the same.
**INSERT **
if (textBox4.Text == "")
{
MessageBox.Show("Please provide Selling1 ", "Item Update", MessageBoxButtons.OK);
textBox4.Focus();
return;
}
int i = dbcon.writer("insert into Item_Master(Item_Code,Name,Description,Selling1,Selling2,Reorder_level,Reorder_Quantity,Active) Values ('" + textBox1.Text + "','" + textBox2.Text + "','" + textBox3.Text + "','" + textBox4.Text + "','" + textBox5.Text + "','" + textBox6.Text + "','" + textBox7.Text + "','" + textBox8.Text + "')");
if (i == 1)
{
MessageBox.Show("Record added succesfully", "Item Table");
Itemview();//disply ll
iclear();
}
else
{ MessageBox.Show("Record unsuccesfully for Item "); }
}
**INSERT **
Dbcontrol dbcon = new Dbcontrol();
SqlDataReader dr = null;
string date = DateTime.Now.ToString("M/d/yyyy");
VIEW/SEARCH
listView1.Items.Clear();
dr = dbcon.reader("select cateid,brand,type,deta,date from emcategory where cateid like '%" + txtseacrchid.Text + "%'");
while (dr.Read())
{
string sid = dr["cateid"].ToString();
string id = dr["brand"].ToString();
string pname = dr["type"].ToString();
string dis = dr["deta"].ToString();
string tim = dr["date"].ToString();
string[] row = { sid, id, pname, dis, tim };
var listViewItem = new ListViewItem(row);
listView1.Items.Add(listViewItem);
}
VIEW/SEARCH*
**UPDATE **
try
{
DialogResult x = MessageBox.Show("Do You Really Want To Update This Record", "Cash Book Details", MessageBoxButtons.YesNo);
if (x == DialogResult.Yes)
{
upate.Enabled = true;
delete.Enabled = false;
foreach (ListViewItem item in listView1.SelectedItems)
{
txtid.Text = item.SubItems[0].Text;
txtBrand.Text = item.SubItems[1].Text;
txttyp.Text = item.SubItems[2].Text;
txtdec.Text = item.SubItems[3].Text;
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
**UPDATE **
DELETE
DialogResult x = MessageBox.Show("Do You Really Want To Delete This Record", "Item Category", MessageBoxButtons.YesNo);
if (x == DialogResult.Yes)
{
delete.Enabled = true;
int i = dbcon.writer("delete from Ritemcategory where cateid='" + txtid.Text + "'");
if (i == 2 || i == 1)
{
MessageBox.Show("Deleted Succesfully", "Item Category");
view();
generatePid();
}
}
else
{
delete.Enabled = false;
}
DELETE
STOREDPROCEDURE
public void generatePid()
{
dr = dbcon.reader("Genarate_itemcategory_id");
while (dr.Read())
{
txtid.Text = dr["value"].ToString();
}
}
//////////////////KEYDOWN////////////
//////////////////
//////////////////KEYPRESS////////////
//////////////////
//////////////////SELECTEDVALUE////////////
private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
upate.Enabled = false;
Save.Enabled = false;
delete.Enabled = true;
foreach (ListViewItem item in listView1.SelectedItems)
{
txtid.Text = item.SubItems[0].Text;
txtBrand.Text = item.SubItems[1].Text;
txttyp.Text = item.SubItems[2].Text;
txtdec.Text = item.SubItems[3].Text;
}
}
//////////////////
//////////////////KEYDOWN////////////
if (e.KeyCode == Keys.Enter)
{
insert();
}
//////////////////
public void log()
{
dr = dbcon.reader("select * from Admin where id = ' 1'");
while (dr.Read())
{
string un = dr["fuser"].ToString();
string ped = dr["fpassword"].ToString();
if ((textBox1.Text == "" || textBox1.Text == null) || (textBox2.Text == "" || textBox2.Text == null))
{
MessageBox.Show("Please enter username and password");
}
else
{
if (textBox1.Text == un && textBox2.Text == ped)
{
logdetail();
}
else
{
MessageBox.Show("User Name or Password is incorrect");
}
}
}
}
//////////////////KEYDOWN////////////
//////////////////
class Dataconnection
{
public static SqlConnection NewCon;
//public static string ConString = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
public static SqlConnection GetConnection()
{
NewCon = new SqlConnection("Data Source=Absar;Initial Catalog=star_fancy_stock;Integrated Security=True;");
return NewCon;
}
}
///////////////////////
2ND
//////////////////
namespace star_fancy_stock
{
class Dbcontrol
{
public static SqlConnection NewCon;
SqlDataReader dr;
public int dataread = 0;
public Dbcontrol()
{ }
public SqlDataReader reader(String sql)
{
try {
NewCon = Dataconnection.GetConnection();
NewCon.Open();
SqlCommand newconn = new SqlCommand(sql, NewCon);
dr = newconn.ExecuteReader();
return dr;
}
catch (Exception ex) { MessageBox.Show(ex.Message); return dr; }
}
public int writer(String sql)
{
try
{
dataread = 0;
NewCon = Dataconnection.GetConnection();
NewCon.Open();
SqlCommand newconn = new SqlCommand(sql, NewCon);
dataread = newconn.ExecuteNonQuery();
NewCon.Close();
return dataread;
}
catch (Exception ex) { MessageBox.Show(ex.Message); return dataread; }
}
}
}
I am using postgresql-8.3-603.jdbc4.jar with jdk 1.6 in my application to do the db operations. I am getting the below exceptions at sometimes and doing restart helps to avoid this exceptions temporarily.
org.postgresql.util.PSQLException: The column name sender_id was not found in this ResultSet.
at org.postgresql.jdbc2.AbstractJdbc2ResultSet.findColumn(AbstractJdbc2ResultSet.java:2502)
at org.postgresql.jdbc2.AbstractJdbc2ResultSet.getString(AbstractJdbc2ResultSet.java:2345)
at org.apache.commons.dbcp.DelegatingResultSet.getString(DelegatingResultSet.java:225)
at org.apache.commons.dbcp.DelegatingResultSet.getString(DelegatingResultSet.java:225)
at com.netcore.bulkrequest.db.FeedDAO.setFeedDetails(FeedDAO.java:142)
at com.netcore.bulkrequest.feed.Feed.getInstance(Feed.java:37)
at com.netcore.bulkrequest.core.BulkRequestTask.(BulkRequestTask.java:86)
at com.netcore.bulkrequest.core.BulkRequestValidate.getBulkRequestTaskObject(BulkRequestValidate.java:104)
at com.netcore.bulkrequest.core.BulkRequestValidate.run(BulkRequestValidate.java:57)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:619)
Here is the code snippet:
public class FeedDAO {
/**
* Database connection pool object
*/
private final DBContext dbc;
private final Feed feed;
public static final String SENDER_ID_ATTRIBUTE = "sender_id";
/**
* Constructor
*
* #param dbc
* #param feed
*/
public FeedDAO(DBContext dbc, Feed feed) {
this.dbc = dbc;
this.feed = feed;
}
public void setFeedDetails() throws SQLException {
String feedDetailsQuery = "SELECT a.priority, b.keyword, b.welcome " +
" FROM feed AS a, pub_feed_info AS b " +
" WHERE a.resource_id = b.resource_id AND b.resource_id = ?";
String senderIdQuery = "SELECT b.attribute_value AS " +
SENDER_ID_ATTRIBUTE + " FROM " +
"attribute_master AS a, feed_attributes AS b " +
"WHERE a.attribute_id = b.attribute " +
" AND a.attribute_name='" + SENDER_ID_ATTRIBUTE + "' " +
" AND feed_id = ?";
Connection con = null;
PreparedStatement fdStmt = null;
PreparedStatement siStmt = null;
try {
con = dbc.getConnection();
//Get the feed details
fdStmt = dbc.getPreparedStatement(con, feedDetailsQuery);
fdStmt.setInt(1, this.feed.getFeedId());
fdStmt.execute();
ResultSet fdResults = fdStmt.getResultSet();
while (fdResults.next()) {
String keyword = fdResults.getString("keyword");
String welcomeMsg = fdResults.getString("welcome");
int priority = fdResults.getInt("priority");
if(null != keyword) {
this.feed.setKeyword(keyword);
} else {
this.feed.setKeyword(String.valueOf(this.feed.getFeedId()));
}
this.feed.setWelcomeMsg(welcomeMsg);
this.feed.setPriority(priority);
}
//Get the sender id
siStmt = dbc.getPreparedStatement(con, senderIdQuery);
siStmt.setInt(1, this.feed.getFeedId());
if(siStmt.execute()) {
ResultSet siResults = siStmt.getResultSet();
while(siResults.next()) {
String senderId = siResults.getString(SENDER_ID_ATTRIBUTE);
this.feed.setSenderId(senderId);
}
} else {
this.feed.setSenderId(Feed.DEFAULT_SENDER_ID);
}
} catch (SQLException ex) {
throw ex;
} finally {
if (fdStmt != null) { fdStmt.close(); }
if (siStmt != null) { siStmt.close(); }
if (con != null) { con.close(); }
}
}
}
Can anyone please help me to find the permanent fix?
Thanks,
Mani
The key part of the error is "The column name sender_id was not found in this ResultSet" -- te very first row. So, how about showing us the query that's looking for a column that's just not there, and maybe the results of executing that query interactively in pgsql, the relevant parts of your schema, etc? Surely you can't expect us to help you debug without seeing anything more than the exception traceback, with zero clues about your code and DB!