I want to display data from a database table into 2 jframes. I tried to do something like that but it doesn't work:
String statut = introducereOrasPlecare.getText();
String url = "jdbc:mysql://localhost:3306/aeroport";
String user = "root";
String password = "elev1Aa.";
PreparedStatement myStmt = null;
ResultSet rs = null;
try{
Connection myConn = DriverManager.getConnection(url, user, password);
myStmt = myConn.prepareStatement("SELECT COUNT(z.nrzbor), SUM(b.valoare)\n" +
"FROM Zboruri z INNER JOIN CUPOANE c ON(z.nrzbor=c.nrzbor) INNER JOIN Bilete b ON(c.nrbilet=b.nrbilet)\n" +
"WHERE z.de_la = ?;");
myStmt.setString(1, statut);
rs = myStmt.executeQuery();
String d = rs.getString("COUNT(z.nrzbor)");
jTextField1.setText(d);
String e = rs.getString("SUM(b.valoare)");
jTextField2.setText(e);
}
catch(Exception e){
System.err.println("Got an exception!");
System.err.println(e.getMessage());
}
}
Could anyone help me?
Related
try{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String url = "jdbc:sqlserver://localhost;databaseName=QLLTCK;integratedSecurity=true;";
Connection connection = DriverManager.getConnection(url);
String sql = "SELECT SUM(soSV) AS sumSoSV FROM PHANCONG WHERE tenMH = 'Công nghệ phần mềm chuyên sâu'";
PreparedStatement pst = connection.prepareStatement(sql);
ResultSet rs = pst.executeQuery();
if(rs.next()){
int SumSoSV = rs.getInt("sumSoSV");
JOptionPane.showMessageDialog(null,"Số sinh viên dự thi: " + SumSoSV);
}
}
catch(Exception sqlex){
JOptionPane.showMessageDialog(null, sqlex);
}
I cannot retrieve the sum of soSV from my PHANCONG table. Its result is 0. When I tried to use String instead of int, its result is null.
Can someone help me? Thanks.
Image
I guess you need to add N before string literal to handle unicode characters:
String sql = "SELECT SUM(soSV) AS sumSoSV FROM PHANCONG WHERE tenMH = N'Công nghệ phần mềm chuyên sâu'"
I have tried to use another proyect and the connection is succesfull but from this proyect I am only able to connect to localhost mysql. I want it to work only on lan.
I am getting "Access denied for user 'root'#'192.168.1.70' (using password: YES)"
Code sample from not working proyect:
Connection con = null;
Statement st = null;
ResultSet rs = null;
try{ con = (Connection) DriverManager.getConnection("jdbc:mysql://"+home.credentials[0],home.credentials[1],home.credentials[2]);
st = (Statement) con.createStatement();
String s = "SELECT * FROM meta";
rs = st.executeQuery(s);
ResultSetMetaData rsmt = rs.getMetaData();
while(rs.next()){
int meta = rs.getInt("meta");
goal.setText(Integer.toString(meta));
}
}catch(Exception e){}
finally{
try{ st.close();
rs.close();
con.close();
}
catch(Exception e){ JOptionPane.showMessageDialog(null, "Información no encontrada");
}
}
Code sample from another proyect which connects succesfully
try
{
// create our mysql database connection
String myDriver = "org.gjt.mm.mysql.Driver";
String myUrl = "jdbc:mysql://192.168.1.66:3306/jjeventoscore";
Class.forName(myDriver);
Connection conn = (Connection) DriverManager.getConnection(myUrl, "root", "");
// our SQL SELECT query.
// if you only need a few columns, specify them by name instead of using "*"
String query = "SELECT * FROM client";
// create the java statement
Statement st = (Statement) conn.createStatement();
// execute the query, and get a java resultset
ResultSet rs = st.executeQuery(query);
// iterate through the java resultset
while (rs.next()){
String name = rs.getString("name");
String last = rs.getString("last");
String h_phone = rs.getString("h_phone");
String m_phone = rs.getString("m_phone");
String of_phone = rs.getString("of_phone");
String ex_phone = rs.getString("ex_phone");
String email = rs.getString("email");
String medium = rs.getString("medium");
System.out.println(name+" "+last);
}
st.close();
}
catch (Exception e)
{
System.err.println("Got an exception! ");
System.err.println(e.getMessage());
}
}
You need to give privileges to the user on that Database and that Table.
With privileges, on your MySQL instance:
USE jjeventoscore;
GRANT ALL ON jjeventoscore.* TO 'root'#'192.168.1.70';
Or maybe try
GRANT ALL ON jjeventoscore.* TO 'root'#'192.168.1.70' IDENTIFIED BY '';
Since it says "Using password: YES"
Also, check the password on MySQL. It should match the parameter in this function
Connection conn = (Connection) DriverManager.getConnection(myUrl, "root", "");
I am using Mysql netbeans . I have created a db table "userdetails_summertrainingproject" . In the login form I have two fileds to fill one is "UUId_JTextField" and other is "Password1_JPasswordField". I want to compare that the password value entered by the user is same as that in db for the particular UUId entered by the user. UUid is unique.
try{
Class.forName("com.mysql.jdbc.Driver");
Connection conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/mysql","root","");
String query = "SELECT password FROM userdetails_summertrainingproject WHERE UUId=?;";
PreparedStatement preparedStatement = conn.prepareStatement(query);
preparedStatement.setString(1,UUId_JTextField.getText());
ResultSet rs = preparedStatement.executeQuery();
char[] password1 = Password1_JPasswordField.getPassword();
String pass1 = new String(password1);
if(rs.getString(query)==pass1){
JOptionPane.showMessageDialog(null, "Logged in successfully");
}
}
catch(Exception e){
System.out.println("Exception in Login:"+e.getMessage());
}
Above is the code I am using.
The Exception is:
Exception in Login:Column 'SELECT password FROM userdetails_summertrainingproject WHERE UUId=?;' not found.
Try this code, you missed rs.next()
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3307/mysql", "root", "");
String query = "SELECT password FROM userdetails_summertrainingproject WHERE UUId=?;";
PreparedStatement preparedStatement = conn.prepareStatement(query);
preparedStatement.setString(1, UUId_JTextField.getText());
ResultSet rs = preparedStatement.executeQuery();
char[] password1 = Password1_JPasswordField.getPassword();
String pass1 = Arrays.toString(password1);
rs.next();
if (rs.getString("password").equals(pass1)) {
JOptionPane.showMessageDialog(null, "Logged in successfully");
}
} catch (Exception e) {
e.printStackTrace();
}
I think it is batter to use another method for get connection string. otherwise you have to write bellow code again and again.
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3307/mysql", "root", "");
EDIT:
public static void main(String[] args) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mysql", "root", "");
String query = "SELECT UUId FROM userdetails_summertrainingproject;";
PreparedStatement preparedStatement = conn.prepareStatement(query);
ResultSet rs = preparedStatement.executeQuery();
rs.next();
String UUId = rs.getString("UUId");
System.out.println("UUId " + UUId);
} catch (Exception e) {
e.printStackTrace();
}
}
Create a class and add this code. then check this code is working or not.
please make sure port, database name, user and password is correct.
If this is give com.mysql.jdbc.CommunicationsException: Communications link failure. most probably your port is incorrect.
I am use these two libraries.
try{
Class.forName("com.mysql.jdbc.Driver");
Connection conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/mysql","root","");
String query="SELECT password FROM tryingtable WHERE name=?;";
PreparedStatement prepstmt=conn.prepareStatement(query);
prepstmt.setString(1,jtf.getText());
ResultSet rs=prepstmt.executeQuery();
rs.next();
String result=rs.getString("password");;
char[] pass = jpf.getPassword();
String password1= new String(pass);
if(result.equals(password1))
JOptionPane.showMessageDialog(null, "go!!");
else
JOptionPane.showMessageDialog(null, "no!!");
}
catch(Exception e){
System.out.println("Exception:"+e.getMessage());
e.getStackTrace();
}
when you want to compare password field to textfield use
char[] pass_char = passwordField.getPassword();
String pass_string = new String(pass_char);
Above code will give you your password field value in string form, then
if(pass_string.equals(textfield))
JOptionPane.showMessageDialog("Password match");
else
JOptionPane.showMessageDialog("Password did not match");
hi every one i have write program that connect to database i create jTextField and jTable my question is how i can use the jTextField to serch in database and view in jTable the code i try is below
try{
String host = "jdbc:derby://localhost:1527/PROCAT";
String uName = "zain";
String uPass = "zain";
Connection con = DriverManager.getConnection( host, uName, uPass);
String sql = "Select * from ITEMB where ITEM '"+asdf.getText()+"'";
stmt = con.createStatement();
rs = stmt.executeQuery(sql);
while (rs.next()) {
String pr = rs.getString("PRISE");
String it= rs.getString("ITEMNAME");
String itm = rs.getString("ITEM");
String[] data = {pr, it, itm};
tabMode.addRow(data);
double price = Double.parseDouble(rs.getString("prise"));
totalpay = price + totalpay;
++rowCount;
}
}
catch (Exception e) {
//ignore
}
jTextField3.setText(String.valueOf(totalpay));
}
Don't ignore the Exception. How to you expect to debug your SQL if you don't display error messages???
I would guess the problem is you are missing an "=" from your select statement (ie. "ITEM = asdf.getText()").
However, the better way to use SQL is to use a PreparedStatement so you don't have to worry about all the delimiters. So the SQL might be something like:
String sql = "Select * from ITEMB WHERE ITEM = ?";
PreparedStatement stmt = connection.prepareStatement(sql);
stmt.setString( 1, asdf.getText() );
stmt.executeQuery();
stmt.close();
It is much easier to read an maintain.
private void btgetinvActionPerformed(java.awt.event.ActionEvent evt) {
if(tf_rmid.getText().length()==11){
JOptionPane.showMessageDialog(null,"REMITTANCE ID IS VALID!");
try {
DBUtil util = new DBUtil();
Connection con = util.getConnection();
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select bk_det.rm_id from bk_det inner join bk_rep on bk_det.rm_id = bk_rep.rm_id WHERE rm_id = ?");
String rm = tf_rmid.getText().trim();
stmt.setString(1, ""+(rm));
while(rs.next()){
int i = rs.getString("RM ID");
String fn = rs.getString("First Name");
String ln = rs.getString("Last Name");
String title = rs.getString("Title");
String city = rs.getString("City");
txtFirstName.setText(fn);
txtLastName.setText(ln);
txtTitle.setText(title);
txtCity.setText(city);
}
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, ex.getMessage());
Logger.getLogger(Demo.class.getName()).log(Level.SEVERE, null, ex);
}
}else{
JOptionPane.showMessageDialog(null,"PLEASE ENTER VALID REMITTANCE ID!");
}
}
I am trying to search values from my database using the select statement but when i am trying to get the value for ? for the where option i am getting error i think its a syntax mistake can ny one please help???
Execute with this,
select bk_det.rm_id from bk_det inner join bk_rep
on bk_det.rm_id = bk_rep.rm_id WHERE bk_det.rm_id = ?
Probably you are missing table name in where clause
It appears a bit odd that you are setting the parameter to the Statement AFTER you execute the query.
Also
int i = rs.getString("RM ID");
this does not compile (if rs is a java.sql.ResultSet instance)
Use a prepared Statement:
String query = "select bk_det.rm_id from bk_det inner join bk_rep on bk_det.rm_id = bk_rep.rm_id WHERE rm_id = ?";
try {
PreparedStatement preps = con.prepareStatement(query);
preps.setString(1, ""+(rm));
preps.execute();
...