I'm new to java programming MySQL I have made a database with Java and managed to insert data but I could not extract the information in certain fields.
This is the code to insert in Mysql:
import java.awt.event.KeyEvent;
import java.sql.*;
import javax.swing.*;
public class Usuario extends javax.swing.JFrame {
Connection conn = null;
PreparedStatement pst = null;
ResultSet rs = null;
private void btguActionPerformed(java.awt.event.ActionEvent evt) {
conn = MySqlConnect.ConnectDB();
String Sql = "INSERT INTO usuarios (nombre, apellidos, nick, pw, usuario) values (?,?,?,?,?)";
try {
pst = conn.prepareStatement(Sql);
pst.setString(1, txno.getText());
pst.setString(2, txap.getText());
pst.setString(3, txni.getText());
pst.setString(4, txpa.getText());
pst.setString(5, txus.getSelectedItem().toString());
int rs = pst.executeUpdate();
if (rs > 0) {
JOptionPane.showMessageDialog(null, "Usuario registrado");
limpiarus();
} else {
JOptionPane.showMessageDialog(null, "un error a ocurrido", "No se registro usuario", JOptionPane.ERROR_MESSAGE);
limpiarus();
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
This would be the code to find the information of Mysql this has a combobox which I put "txus":
private void btbuActionPerformed(java.awt.event.ActionEvent evt) {
conn = MySqlConnect.ConnectDB();
String Sql = "SELECT *FROM usuarios where nick=?";
try {
pst = conn.prepareStatement(Sql);
pst.setString(1, txni.getText());
if (rs.next()){
txno.setText(rs.getString("nombre"));
txap.setText(rs.getString("apellidos"));
txni.setText(rs.getString("nick"));
txpa.setText(rs.getString("pw"));
txus.setSelectedItem(rs.getString("usuario"));
}else {
JOptionPane.showMessageDialog(null, "incorrecto", "accso denegado", JOptionPane.ERROR_MESSAGE);
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
This is my connection to mysql
package Secure;
import java.sql.*;
import javax.swing.*;
public class MySqlConnect {
Connection conn=null;
public static Connection ConnectDB() {
try{
Class.forName("com.mysql.jdbc.Driver");
Connection conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/basededatos", "root","1002478900k");
JOptionPane.showMessageDialog(null, "Conectado a la base de datos");
return conn;
}
catch (Exception e){
JOptionPane.showMessageDialog(null, e);
return null;
}
}
}
When executing the button it shows me an error java.langNullPointerException apparently the main problem is in the code of the search button.
Sorry for not summarizing the question but I feel it is necessary.
Thanks in advance and have a nice day.