private void totaleActionPerformed(java.awt.event.ActionEvent evt) {
PreparedStatement ps;
ResultSet rst;
String query="SELECT SUM( montant_m) FROM `mnd` ";
String num_m = jTF1.getText();
try {
ps=Connecteur_db.connecterDB().prepareStatement(query);
// ps.setString(1, num_m);
rst=ps.executeQuery();
if(rst.next()){
String som_t = rst.getString("SUM(montant_m)");
jLabe_resultat.setText(""+som_t);
JOptionPane.showMessageDialog(null,""+som_t);
}
} catch (SQLException ex) { java.util.logging.Logger.getLogger(noveau_j.class.getName()).log(Level.SEVERE, null, ex);
}
}
While trying to execute this i am getting an error like "Caused by: java.sql.SQLException: Column 'SUM(montant_m)' not found.
at What is the problem here?? Please help me..
Sorry for my poor english
This is myconnecteur_db() class the connection
public static Connection connecterDB() {
Connection conx = null;
String pilot = "com.mysql.cj.jdbc.Driver";
try {
Class.forName(pilot);//chargement de driver
System.out.println("Driver ok");
String url = "jdbc:mysql://localhost:3307/tc";
String user = "root";
String pw;
pw = "root";
Connection con = DriverManager.getConnection(url, user, pw);
System.out.println("la connection est bien etablir");
return con;
} catch (Exception e) {
System.out.println("Echec connection!!");
e.printStackTrace();
return null;
}
}
I assume this is occuring at the line rst.getString("SUM(montant_m)")
SUM(montant_m) doesn't have a space before montant_m.
To make it easier, use the query:
SELECT SUM(montant_m) AS total FROM mnd
And then rst.getString("total")
Related
I would like to ask how to make Connection con = getConnection(); becaome a primer or main variable so that it would not connect to SQL database every function made. Because as you can see on my codes, every function/class has Connection con = getConnection(); so it connects to the database every function. It makes my program process slowly. Please help thank you.
package march30;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Arrays;
public class sqltesting {
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
get();
}
public static void lookup() throws Exception{
try {
Connection con = getConnection();
PreparedStatement statement = con.prepareStatement("SELECT first,last FROM tablename where id=6");
ResultSet result = statement.executeQuery();
if (result.next()) {
System.out.println("First Name: " + result.getString("first"));
System.out.println("Last Name: " + result.getString("last"));
}
else {
System.out.println("No Data Found");
}
} catch (Exception e) {}
}
public static ArrayList<String> get() throws Exception{
try {
Connection con = getConnection();
PreparedStatement statement = con.prepareStatement("SELECT first,last FROM tablename");
ResultSet result = statement.executeQuery();
ArrayList<String> array = new ArrayList<String>();
while (result.next()) {
System.out.print(result.getString("first"));
System.out.print(" ");
System.out.println(result.getString("last"));
array.add(result.getString("last"));
}
System.out.println("All records have been selected!");
System.out.println(Arrays.asList(array));
return array;
} catch (Exception e) {System.out.println((e));}
return null;
}
public static void update() throws Exception{
final int idnum = 2;
final String var1 = "New";
final String var2 = "Name";
try {
Connection con = getConnection();
PreparedStatement updated = con.prepareStatement("update tablename set first=?, last=? where id=?");
updated.setString(1, var1);
updated.setString(2, var2);
updated.setInt(3, idnum);
updated.executeUpdate();
} catch (Exception e) {System.out.println((e));}
finally{
System.out.println("Update Completed");
}
}
public static void delete() throws Exception{
final int idnum = 7;
try {
Connection con = getConnection();
PreparedStatement deleted = con.prepareStatement("Delete from tablename where id=?");
deleted.setInt(1, idnum);
deleted.executeUpdate();
} catch (Exception e) {System.out.println((e));}
finally{
System.out.println("Delete Completed");
}
}
public static void post() throws Exception{
final String var1 = "Albert";
final String var2 = "Reyes";
try {
Connection con = getConnection();
PreparedStatement posted = con.prepareStatement("INSERT INTO tablename (first, last) VALUES ('"+var1+"', '"+var2+"')");
posted.executeUpdate();
} catch (Exception e) {System.out.println((e));}
finally{
System.out.println("Insert Completed");
}
}
public static void createTable() throws Exception {
try {
Connection con = getConnection();
PreparedStatement create = con.prepareStatement("CREATE TABLE IF NOT EXISTS tablename(id int NOT NULL AUTO_INCREMENT, first varchar(255), last varchar(255), PRIMARY KEY(id))");
create.executeUpdate();
} catch (Exception e) {System.out.println((e));}
finally{
System.out.println("Function Completed");
}
}
public static Connection getConnection() throws Exception{
try {
String driver = "com.mysql.cj.jdbc.Driver";
String url = "jdbc:mysql://xxxxxxxx.amazonaws.com:3306/pointofsale";
String username = "xxxxx";
String password = "xxxxxx";
Class.forName(driver);
Connection conn = DriverManager.getConnection(url,username,password);
return conn;
} catch (Exception e) {System.out.println(e);}
return null;
}
}
To solve your problem you need to store a Connection object in your sqltesting class as a class member. You then need to reference the Connection object instead of getConnection(). It's also worth mentioning that Connection is a AutoClosable object so you need to close this resource when you're done with it, I.E; on application disposal. You also might want to consider using a connection pooling API like Hikari or C3P0 so you can open and close connections when you need them instead of having 1 open for a long time.
class SQLTesting {
private final Connection connection;
public SQLTesting(Connection connection) {
this.connection = connection;
}
public SQLTesting() {
this(getConnection());
}
// other methods
private Connection getConnection() {
// your method to create connection, rename to createConnection maybe.
}
}
I'm trying to set up JDBC but I'm getting this error.
I tried adding the dependency in pom.xml and even jar file nothing works. I tried the methods mentioned in previous questions, nothing works.
public class FilmLength {
public static void main(String[] args) throws SQLException {
Connection dbCon = null;
PreparedStatement st = null;
ResultSet rs = null;
String url = "jdbc:mysql//localhost:3306/sakila";
String username = "devuser";
String password = "Demo#123";
String query = "select * from film ";
try {
Class.forName("com.mysql.jdbc.Driver");
dbCon = DriverManager.getConnection(url,username,password);
st = dbCon.prepareStatement(query);
rs = st.executeQuery();
while(rs.next()) {
String title = rs.getString(1);
System.out.println(title);
}
} catch (Exception e) {
e.printStackTrace();
}
finally {
dbCon.close();
st.close();
rs.close();
}
}
}
Instead of
String url = "jdbc:mysql//localhost:3306/sakila";
it should be
String url = "jdbc:mysql://localhost:3306/sakila";
Am trying to save some field from my jFrame form but when i click the save button, i get the null pointer exception. Previously i was getting the errors that text field couldn't be null so i unchecked not null but it didn't work , i decided not to include Voucher_no in MySQL insert statement as it is an auto increment and its text field is not editable
Is there any problem with my code?
Am Using Mysql Workbench.
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/canning?zeroDateTimeBehavior=convertToNull", "root", "");
con.setAutoCommit(false);
try {
// String kb = jTextField3.getText(); //voucher_no
String kc = (String) jComboBox3.getSelectedItem(); //factory
String kg = jTextField10.getText(); //fuel
Double ks = Double.valueOf(kg);
String ke = jTextField11.getText(); //electricity
Double kt = Double.valueOf(ke);
String kf = jTextField12.getText(); //manpower
Double ku = Double.valueOf(kf);
String kj = (String) jComboBox4.getSelectedItem(); //can_name
String kk = (String) jComboBox5.getSelectedItem(); //label name
String kq = jTextField23.getText();//no_of_cans
Double kv = Double.valueOf(kq);
String kr = jTextField24.getText();//no_of_labels
Double kw = Double.valueOf(kr);
String query1= "insert into production (date,factory,fuel,electricity,manpower,can_name,label_name,no_of_cans,no_of_labels)"
+ "values (?,?,?,?,?,?,?,?,?)";
try (PreparedStatement pst = con.prepareStatement(query1)){
// pst.setString(10, kb);
pst.setString(1, ((JTextField) jDate1.getDateEditor().getUiComponent()).getText());
pst.setString(2, kc);
pst.setDouble(3, ks);
pst.setDouble(4, kt);
pst.setDouble(5, ku);
pst.setString(6, kj);
pst.setString(7, kk);
pst.setDouble(8, kv);
pst.setDouble(9, kw);
pst.execute();
}
try {
int rows = jTable2.getRowCount();
for (int row = 0; row < rows; row++) {
String kd = (String) jTable2.getValueAt(row, 0);
Double kn = (Double) jTable2.getValueAt(row, 1);
try {
// Class.forName("com.mysql.jdbc.Driver").newInstance();
// Connection con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/canning?zeroDateTimeBehavior=convertToNull", "root", "");
String query = "insert into production(product_name,product_quantity)"
+ "values (?,?)";
PreparedStatement update = con.prepareStatement(query);
update.setString(1, kd);
update.setDouble(2, kn);
update.addBatch();
update.executeBatch();
con.commit();
} catch (SQLException e) {
e.printStackTrace();
// JOptionPane.showMessageDialog(this, "Error in production Table");
}
}
} catch (Exception e) {
JOptionPane.showMessageDialog(this, "Invalid Entry in fields");
}
} catch (Exception e) {
e.printStackTrace();
// JOptionPane.showMessageDialog(null, "Invalid in fields");
}
} catch (Exception e) {
e.printStackTrace();
}
The code is doing
update.addBatch();
update.executeBatch();
con.commit();
executeBatch and commit must be done outside the loop.
The misunderstanding arises from "addBatch" that should have been named "addToBatch."
Try doing it this way. First create a connection class as follows;
import java.sql.Connection;
import java.sql.DriverManager;
public class db_connection
{
public Connection connection()
throws Exception
{
try
{
Connection conn = null;
String username = "root"; String password = "";
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/database";
try {
Class.forName(driver);
} catch (Exception e) {
e.printStackTrace();
return null;
}
conn = DriverManager.getConnection(url, username, password);
conn.setAutoCommit(false);
return conn;
} catch (Exception e) {
e.printStackTrace();
System.exit(0);
}return null;
}
}
Then on your save button do something like this,
private void ButtonRegGroup_SubmitActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
if ((this.jTextFieldGrp_ReqAmnt.getText().equals(""))
|| (this.jTextFieldGrp_name.getText().equals(""))
|| (this.jTextFieldGrp_Id.getText().equals(""))
|| (this.jTextFieldGrp_prj_name.getText().equals(""))) {
JOptionPane.showMessageDialog(this, "Some fields are empty", this.title, this.error);
} else {
try {
this.con = ((Connection) new db_connection().connection());
this.pst = ((PreparedStatement) this.con.prepareStatement("insert into registered_projects(project_type,name,project_name,project_id,constituency,ward,requested_amount)values(?,?,?,?,?,?,?)"));
GroupRegDetails();
this.pst.setString(1, this.proj_type);
this.pst.setString(2, this.group_name);
this.pst.setString(3, this.proj_name);
this.pst.setInt(4, this.proj_id);
this.pst.setString(5, this.constituency);
this.pst.setString(6, this.ward);
this.pst.setInt(7, this.requested_amount);
int row = this.pst.executeUpdate();
con.commit();
if (row == 0) {
this.con.rollback();
JOptionPane.showInternalMessageDialog(this, "Didn't Register project", this.title, this.error);
}
JOptionPane.showMessageDialog(this, "Project Successfully Registered", this.title, this.infor);
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void GroupRegDetails() {
this.group_name = this.jTextFieldGrp_name.getText();
this.proj_id = Integer.parseInt(this.jTextFieldGrp_Id.getText());
this.proj_name = this.jTextFieldGrp_prj_name.getText();
this.constituency = this.jComboBoxGrp_Comb_const.getSelectedItem().toString();
this.ward = this.jComboBoxGrp_comb_Ward.getSelectedItem().toString();
this.requested_amount = Integer.parseInt(this.jTextFieldGrp_ReqAmnt.getText());
this.proj_type = "Group";
}
And finally good practice is to put fields on a Jpanel and the Jpanel on a Jframe. Hope this helps.
The below code always generates a NullPointerException error.
The connection:
Connection con;
java.sql.PreparedStatement st;
public void Connect()
{
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
String user = "root";
String password = "";
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mpdb",user,password);
String sql = new String("SELECT * FROM 'dati' WHERE user =? and pass =?");
st = con.prepareStatement(sql);
}catch(Exception ex){
JOptionPane.showMessageDialog(null, "Connessione non riuscita");
ex.printStackTrace();
}
}
The login:
#SuppressWarnings("deprecation")
public void mouseClicked(MouseEvent arg0) {
TextFields tf = new TextFields();
Driver d = new Driver();
try{
String sql = new String("SELECT user,pass FROM 'dati' WHERE user =? and pass =?");
ps = d.con.prepareStatement(sql);
ps.setString(1,tf.ftf.getText()); //JFormattedTextField
ps.setString(2,tf.pf.getText()); //JPasswordField
rs = ps.executeQuery();
if(rs.next()){
JOptionPane.showMessageDialog(null, "User successfully logged");
}else{
JOptionPane.showMessageDialog(null, "User not found");
}
}catch(Exception ex){
ex.printStackTrace();
}
}
The select statement is wrong. Single quotes (') denote string literals in SQL, not object names (in your case - the table name). Since the SQL is invalid, no result set can be created, and hence the exception.
To resolve this, you should remove the quotes around 'dati':
String sql = "SELECT user,pass FROM dati WHERE user =? and pass =?"
I resolved with this code:
Execute connection:
package main;
import java.sql.Connection;
import java.sql.DriverManager;
import javax.swing.JOptionPane;
public class Driver {
Connection con = null;
public static Connection Join()
{
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
String user = "root";
String password = "";
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mpdb",user,password);
return con;
}catch(Exception ex){
JOptionPane.showMessageDialog(null, "Connessione non riuscita");
ex.printStackTrace();
return null;
}
}
}
Login Button:
#SuppressWarnings("deprecation")
public void mouseClicked(MouseEvent arg0) {
TextFields tf = new TextFields();
String sql = new String("SELECT * FROM `dati` WHERE user = ? and pass = ?");
try{
ps = con.prepareStatement(sql);
ps.setString(1,tf.ftf.getText().trim());
ps.setString(2,tf.pf.getText().trim());
rs = ps.executeQuery();
if(rs.next()){
JOptionPane.showMessageDialog(null, "Login effettuato");
}else{
JOptionPane.showMessageDialog(null, "Utente o password non corretti");
}
}catch(Exception ex){
ex.printStackTrace();
}
}
public void mousePressed(MouseEvent arg0) {
}
public void mouseReleased(MouseEvent arg0) {
}
});
But now I've a new problem: the program do its work but it doesn't compare correctly the password. How do I have to proceed?
I'm currently being thrown into the depths by my school and they are expecting me to program a simple login form using sql. They have given us brief examples on how they use JDBC and what it all is, but haven't really explained step by step how to use it on our own. Therefore i have snatched a bit of code from an example but i'm unable to get it working. I keep receiving an nullpointerexception and i can't figure out why :(
Here's the connection class:
package Database;
import java.sql.*;
public class MySQLConnection {
public static final String DRIVER = "com.mysql.jdbc.Driver";
public static final String DBURL = "jdbc:mysql://localhost/corendon";
public static final String DBUSER = "root";
public static final String DBPASS = "simplepass";
private ResultSet result = null;
private int affectedRows = -1;
Connection conn = null;
public void startConnection() {
try {
Class.forName(DRIVER);
DriverManager.setLoginTimeout(5);
conn = DriverManager.getConnection(DBURL, DBUSER, DBPASS);
} catch (Exception e) {
}
}
public void closeConnection() {
try {
if (conn != null && !conn.isClosed()) {
conn.close();
}
} catch (Exception e) {
}
conn = null;
}
public ResultSet performSelect(PreparedStatement prdstmt) throws SQLException {
result = prdstmt.executeQuery();
return result;
}
public int performUpdate(PreparedStatement prdstmt) throws SQLException {
affectedRows = prdstmt.executeUpdate();
return affectedRows;
}
public Connection getConnection() {
return conn;
}
}
And here is the method i'm getting the exception in (in a different class):
MySQLConnection conn = new MySQLConnection();
public void compareData(int id, String pass) throws SQLException{
ResultSet rs = null;
PreparedStatement prdstmt = null;
String query = "SELECT id, password FROM users WHERE id=?, password=?";
conn.startConnection();
prdstmt = conn.getConnection().prepareStatement(query);
prdstmt.setInt(1, id);
prdstmt.setString(2, pass);
rs = conn.performSelect(prdstmt);
while (rs.next()){
String tempPass = rs.getString("password");
int tempId = rs.getInt("id");
}
if(conn != null){
conn.closeConnection();
}
}
I'm getting the nullpointerexception on line:
prdstmt = conn.getConnection().prepareStatement(query);
Why does it throw an exception there, but not when i start the connection and also how do i solve this? Thanks in advance.
When you call startConnection(), you are throwing an Exception
public void startConnection() {
try {
Class.forName(DRIVER);
DriverManager.setLoginTimeout(5);
conn = DriverManager.getConnection(DBURL, DBUSER, DBPASS);
} catch (Exception e) {
//An exception occurs here, but you don't do anything about it
}
}
Therefore, when you call getConnection(), the conn variable is still null, which is throwing the NullPointerException.
Either make startConnection() throw an exception so that you're forced to deal with it (this is usually how most JDBC drivers work anyway), or check to see if the conn variable is null before you start using it.
public void compareData(int id, String pass) throws SQLException{
ResultSet rs = null;
PreparedStatement prdstmt = null;
String query = "SELECT id, password FROM users WHERE id=?, password=?";
conn.startConnection();
if (conn.getConnection() == null) {
throw new SQLException("Connection is null!");
}
Or (what I think would personally be better)
public void startConnection() throws Exception {
Class.forName(DRIVER);
DriverManager.setLoginTimeout(5);
conn = DriverManager.getConnection(DBURL, DBUSER, DBPASS);
}
public void compareData(int id, String pass) throws SQLException{
ResultSet rs = null;
PreparedStatement prdstmt = null;
String query = "SELECT id, password FROM users WHERE id=?, password=?";
try {
conn.startConnection();
} catch (Exception e) {
throw new SQLException(e);
}
Also as a tip, you should probably avoid declaring your classes as the same name of other classes you are using. This is all happening in your own MySQLConnection class, but that could be confusing with the actual com.mysql.jdbc.MySQLConnection class.