Returning ResultSet without close? - java

I would like to have a database connection managing class which I can use for simple SQL commands like SELECT, INSERT etc. by simple calling something like this (class below):
ResultSet test = DataService.getResultSet("SELECT NOW()");
test.first();
System.out.println(test.getString(1));
This is class I've found on web:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
* Database object to load drivers and perform queries
* #author Abdulsalam Umar blog.salamtura.com
*/
public class DataService {
private static Connection con;
private static final String Driver = "oracle.jdbc.driver.OracleDriver";
private static final String ConnectionString = "Your database connection string";
private static final String user = "username";
private static final String pwd = "password";
/**
* create Database object
*/
public DataService() {
}
/**
* to load the database base driver
* #return a database connection
* #throws SQLException throws an exception if an error occurs
*/
public static Connection loadDriver() throws SQLException {
try {
Class.forName(Driver);
} catch (ClassNotFoundException ex) {
System.out.println(ex.getMessage());
}
con = DriverManager.getConnection(ConnectionString, user, pwd);
return con;
}
/**
* to get a result set of a query
* #param query custom query
* #return a result set of custom query
* #throws SQLException throws an exception if an error occurs
*/
public static ResultSet getResultSet(String query) throws SQLException {
Connection con = loadDriver();
ResultSet rs;
PreparedStatement st = con.prepareStatement(query);
rs = st.executeQuery();
return rs;
}
/**
* to run an update query such as update, delete
* #param query custom query
* #throws SQLException throws an exception if an error occurs
*/
public static void runQuery(String query) throws SQLException {
Connection con = loadDriver();
ResultSet rs;
PreparedStatement st = con.prepareStatement(query);
st.executeUpdate();
}
}
Is this way of returning ResultSet without closing it (and closing the statement) right? How can I return the ResultSet from the method?

Returning result set is not a good idea. So,fetch the required data and make use of collection to return the data.
This answer may be useful

How about passing a callback that takes ResultSet as parameter and let client code do whatever needs to inside it while you make sure that everything is cleaned up afterwards.
This is pattern in used in spring JDBC ResultSetExtractor and RowMapper. Look at this answer.

You can't return ResultSet because it will be closed when method destroyed. But you can get raw data from ResultSet, try this:
public ArrayList<ArrayList<byte[]>> getResultQuery(String query){
ArrayList<ArrayList<byte[]>> tableResult = new ArrayList<>();
ArrayList<byte[]> row;
conn = getConnection(db_url);
try {
Statement statement = conn.createStatement();
ResultSet resultSet = statement.executeQuery(query);
int countColumn = resultSet.getMetaData().getColumnCount();
if (countColumn==0) return null;
while (resultSet.next()){
row = new ArrayList<>();
for (int i = 0; i<countColumn; i++){
row.add(i,resultSet.getBytes(i+1));
}
tableResult.add(row);
}
} catch (SQLException e) {
e.printStackTrace();
}
return tableResult;
}
public static Connection getConnection (String db_url){
Connection conn = null;
try{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
conn = DriverManager.getConnection(db_url);
}catch(Exception e){
e.printStackTrace();
}
return conn;
}
In this, i try to return ArrayList of ArrayList<byte[]>, ArrayList<byte[]> = 1 row in ResultSet. If you want to get some value, just use row.get(i) to get value from column i+1 in ResultSet which look like a 2 dimensions Matrix

Related

How to Connect on a different database in Try-Catch in Java?

I'll try my best to make this as clear as possible since I'm new to Java. If there are parts which are unclear to you, please let me know. I apologize beforehand if the structure of my coding is messy.
I'm making a combobox event wherein if an item is selected (or changed), it will display items of that database and if the Update button is clicked, the program will connect to the database based on the item selected in the combobox.
The problem is that the variable cn after the if-else statement, has an error of "variable may have not been initialized".
Please note that I would like to focus on the condition since it is where I'm having difficulties and that the Update part is not a concern at this time.
private void btn_UpdateActionPerformed(java.awt.event.ActionEvent evt)
{
String value2 = (String) combobox_location.getSelectedItem();
String value4 = (String) combobox_category.getSelectedItem();
try
{
if(value2.equals(value4))
{
Connection cn = db.itemconnector.getConnection();
}
String sql = "UPDATE items set location = '"+value2+"' where id = '"+value4+"' " ; //Please ignore this line for the now
PreparedStatement ps1 = cn.prepareStatement(sql);
ps1.execute();
JOptionPane.showMessageDialog(null, "Update Successful");
PreparedStatement ps2 = cn.prepareStatement(ref);
ResultSet rs = ps2.executeQuery();
DefaultTableModel tm = (DefaultTableModel)itemTable.getModel();
tm.setRowCount(0);
while(rs.next())
{
Object o[] = {rs.getInt("id"), rs.getString("location"), rs.getString("product_name"),rs.getString("product_category"),rs.getString("product_description"),rs.getInt("product_stock"), rs.getFloat("product_price"), rs.getString("product_status")};
tm.addRow(o);
}
}
catch (Exception e)
{
System.out.println("Update Error!");
}
}
I have a package db that has itemconnector class for database connection and here is my code I've written in it. I hope I have provided all necessary details for your assistance. If you need more info, please let me know. Thank you.
package db;
import java.sql.*;
public class itemconnector {
/**
*
* #return
* #throws Exception
*/
public static Connection getConnection() throws Exception
{
Class.forName("com.mysql.jdbc.Driver");
Connection cn = (Connection)
DriverManager.getConnection("jdbc:mysql://192.168.1.50:3306/sales","root","");
return cn;
}
public static Connection getConnection1() throws Exception
{
Class.forName("com.mysql.jdbc.Driver");
Connection cn = (Connection)
DriverManager.getConnection("jdbc:mysql://192.168.1.50:3306/sales1","root","");
return cn;
}
public static Connection getConnection2() throws Exception
{
Class.forName("com.mysql.jdbc.Driver");
Connection cn = (Connection)
DriverManager.getConnection("jdbc:mysql://192.168.1.50:3306/sales2","root","");
return cn;
}
}

Learn to program in Java Servlet connection to db

I'm learning to program in java and the use of servlet and jsp page.
I have some trouble understanding how I can make the connection with the database.
In particular I have a Java page called Database.java where I create the connection with the database and in which there are all the functions that are performed.
And I created a page called Prenotation.java where I have to do some actions. My problem is that I would not like to leave the database connection on this page (as you can see from the code) but I would like to make the connection via the Database.java page.
I've tried several times but I do not understand how I can do it.
Can you give me some advice? Thank you.
Database.java
package db;
import java.math.BigDecimal;
import java.sql.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.concurrent.TimeUnit;
import entity.*;
public class Database {
private Connection connection = null;
private PreparedStatement statement = null;
private ResultSet rs = null;
private String dbname = "Hotel";
String nomeutente = "root";
String password = "123456789";
private static Database db = null;
public static synchronized Database getDatabase() {
if (db == null) {
db = new Database();
}
return db;
}
private Database() {
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/" + dbname
+ "?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC",
nomeutente, password);
} catch (Exception exc) {
exc.printStackTrace();
}
}
public Connection getConnection() {
return connection;
}
public boolean checkUser(String email, String password) throws SQLException {
boolean result = false;
String query = "select password from users where email=?";
statement = connection.prepareStatement(query);
statement.setString(1, email);
rs = statement.executeQuery();
if (rs.next() && password.equals(rs.getString("password"))) {
result = true;
}
rs.close();
statement.close();
return result;
}
public boolean existingMail(String email) throws SQLException {
String query = "select * from users where email=?";
boolean result = true;
statement = connection.prepareStatement(query);
statement.setString(1, email);
rs = statement.executeQuery();
if (rs.next()) {
result = true;
} else {
result = false;
}
rs.close();
statement.close();
return result;
}
public boolean insertUtente(Utente u,String password) throws SQLException {
String query = "INSERT INTO users (email,nome,cognome,luogodinascita,datadinascita,indirizzo,password) VALUES (?,?,?,?,?,?,?)";
if(existingMail(u.getEmail())) {
return false;
}
statement = connection.prepareStatement(query);
statement.setString(1, u.getEmail());
statement.setString(2, u.getNome());
statement.setString(3, u.getCognome());
statement.setString(4, u.getLuogodinascita());
statement.setString(5, u.getDatadinascita());
statement.setString(6, u.getIndirizzo());
statement.setString(7, password);
statement.execute();
statement.close();
return true;
}
public Utente getUtente(String email) throws SQLException {
String query= "select * from users where email=?";
statement = connection.prepareStatement(query);
statement.setString(1, email);
rs=statement.executeQuery();
if(!rs.next()) {
return null;
}
Utente u=new Utente(email,rs.getString("nome"),rs.getString("cognome"),rs.getString("datadinascita"),rs.getString("luogodinascita"),rs.getString("indirizzo"));
rs.close();
statement.close();
return u;
}
public boolean modificaPassword(String email, String password) throws SQLException {
String query="UPDATE users SET password='"+password+"' WHERE email='"+email+"'";
Statement statement=connection.createStatement();
statement.executeUpdate(query);
statement.close();
return true;
}
public boolean modificaProfilo(Utente u) throws SQLException {
String query="UPDATE users SET nome = ?, cognome = ?, datadinascita = ?, luogodinascita = ?, indirizzo = ? WHERE email = ?";
statement = connection.prepareStatement(query);
statement.setString(1, u.getNome());
statement.setString(2, u.getCognome());
statement.setString(3, u.getDatadinascita());
statement.setString(4, u.getLuogodinascita());
statement.setString(5, u.getIndirizzo());
statement.setString(6, u.getEmail());
statement.executeUpdate();
statement.close();
return true;
}}
This instead is the page of which I speak
package servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.swing.JOptionPane;
import db.Database;
import entity.Prenotazione;
/**
*
* #author OOPs
*/
public class Prenotation extends HttpServlet {
private static final String ResultSet = null;
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session=request.getSession();
String idPrenotazione = request.getParameter("idPrenotazione");
String email = request.getParameter("email");
int typeRoom = Integer.parseInt(request.getParameter("typeRoom"));;
String arrivalDate = request.getParameter("arrivalDate");
String departureDate = request.getParameter("departureDate");
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
Class.forName("com.mysql.cj.jdbc.Driver");
// out.println("driver loaded");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/Hotel?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC","root" ,"123456789");
out.println("Connect");
Statement st = con.createStatement();
// Statement stmt = con.createStatement();
out.println("connection successfull");
int total = 0;
PreparedStatement ps = con.prepareStatement( "SELECT COUNT(*) as total FROM reservation WHERE typeRoom = ? AND (? >= arrivaldate AND ? <= departuredate) OR (? >= arrivaldate AND ? <= departuredate)");
int c = 0;
ps.setInt(++c, typeRoom);
ps.setString(++c, arrivalDate);
ps.setString(++c, departureDate);
ps.setString(++c, arrivalDate);
ps.setString(++c, departureDate);
ResultSet rs = ps.executeQuery();
// ResultSet rs2 = stmt.executeQuery(check);
out.println("<h1> Stringa check eseguito </h1>");
if( total > 0) {
// response.sendRedirect("home.jsp");
response.sendRedirect("PrenotazioneNegata.jsp");
}
else {
st.executeUpdate("insert into reservation (email,typeRoom,arrivalDate,departureDate)values ('"+email+"','"+typeRoom+"','"+arrivalDate+"','"+departureDate+"')");
response.sendRedirect("PrenotazioneAvvenuta.jsp");
}
out.println("<h1> Registrazione Eseguita </h1>");
}catch(Exception e){
out.println("Errore." +e);
}
finally {
out.close();
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* #return a String containing servlet description
*/
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
A web container will typically route requests to the same servlet instance so it needs to be thread safe. Currently, the Database class provides a single connection, which would be used by concurrent requests so it is not thread safe.
Consider creating something like a ConnectionFactory class. For example:
public class ConnectionFactory {
public Connection getConnection() {
// move all the creation code from Database class to here
// create and return a new instance
}
}
Then modify the Database class to use the factory
public class Database {
private final ConnectionFactory connectionFactory;
public Database(ConnectionFactory connectionFactory) {
this.connectionFactory = connectionFactory;
}
// change to private and use the factory
private Connection getConnection() {
return connectionFactory.getConnection();
}
// example method to be used by servlet
public int getTotalReservations(int typeRoom, String arrivalDate, departureDate) {
// query related code currently in serlvet goes here...
}
}
And use the servlet lifecycle init() method to create the objects so the servlet can use it. For example:
public class Prenotation extends HttpServlet {
private Database database;
#Override
public void init() throws ServletException {
super.init();
this.database = new Database(new ConnectionFactory()); // no statics needed!
}
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session=request.getSession();
String idPrenotazione = request.getParameter("idPrenotazione");
String email = request.getParameter("email");
int typeRoom = Integer.parseInt(request.getParameter("typeRoom"));;
String arrivalDate = request.getParameter("arrivalDate");
String departureDate = request.getParameter("departureDate");
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
// use the method from `Database` which knows how to query the DB.
int totalReservations = database.getTotalReservations(typeRoom, arrivalDate, departureDate);
// more processing... and forward to the JSP
}
Note that Database now refers to both a USERS table and a RESERVATTIONS table. It would be better to split these into separate classes, such as UsersQuery and ReservationsQuery. They can both share the same ConnectionFactory instance.
See also:
single responsibility principle
inversion of control (injecting ConnectionFactory into Database)
servlet lifecycle
why static variables (or singletons) are/can be evil
DataSource (instead of the low level ConnectionFactory)

SQLite connection w/ Libgdx .Desktop

Well, I'm trying to use SQLite in my Libgdx game, but don't know how.
public class Main {
public static void main(String[] args){
LwjglApplicationConfiguration config = new LwjglApplicationConfiguration();
config.title = Game.TITLE;
config.width = Game.V_WIDTH * Game.SCALE;
config.height = Game.V_HEIGHT * Game.SCALE;
new LwjglApplication(new Game(), config);
}}
What I need to do in my main? lol
I've been looking for this but, all I can find is related to Android application.
I already have the driver in my ref libraries, and connection class..
What I usually do when using a database with an application, is make a ConnectionFactory, that returns a new connection to the database.
public class ConnectionFactory {
public static Connection getConnection() {
Connection con = null;
Class.forName("org.sqlite.JDBC");
con = DriverManager.getConnection("jdbc:sqlite:test.db"); //change to whatever db you want
return con;
}
}
now we have a ConnectionFactory that can pump out connections to our database. Now when we want to interact with the database, you can get the connection appropriately. inside your main, it might look something like this:
public static void main(String[] args) {
Connection con = null;
String firstName = null, lastName = null;
try {
con = ConnectionFactory.getConnection();
PreparedStatement pstmt = con.prepareStatement("SELECT * FROM myTable where myId = ?");
pstmt.setInt(1, /*some id here, ill put this as example:*/ 1234567);
//execute the query and put into result set so we can get the values.
ResultSet rs = pstmt.executeQuery();
//the resultset iterates through rows, by calling next
if( rs.next() ) //could be while(rs.next()) if expecting multiple rows
{
firstName = rs.getString("firstName"); //column name you want to grab here
lastName = rs.getString("lastName");
}
} catch(SQLException sqle) {
sqle.printStackTrace();
}
finally {
try {
con.close(); //dont forget to close your connection to database!
} catch(SQLException sqle) {
sqle.printStackTrace();
}
}
}
You will need to create tables within the SQLite database and insert records before you can do any interactions though, so keep that in mind.

How to use Runnable and Threads in this code

I am facing problem. We are writting Java application as school project and we are supposed to use threads. Obviously, the application is not as complex to require threads, but we have to have them.
We decided to use threads for database communication, but we are not sure, how to use them for single methods. We created Database Transfer Object with some methods to insert entities into DB. How to use Runnable for single methods, please? To be more specific, we would like to create Runnable in methods and then add it to thread pool, but then, we would be able to get returns back.
public class EmployeeDTO {
private Employee employee;
private Connection conn;
private int id_employee;
/**
* Database connection
* #throws ClassNotFoundException
* #throws SQLException
*/
public EmployeeDTO() throws ClassNotFoundException, SQLException {
DatabaseConnection dbcon = new DatabaseConnection();
conn = dbcon.getConnection();
}
public EmployeeDTO(Employee employee) throws ClassNotFoundException, SQLException {
this.employee = employee;
DatabaseConnection dbcon = new DatabaseConnection();
conn = dbcon.getConnection();
}
/**
* Insert new Employee into database and sets it's id
* #param emp
* #throws SQLException
*/
public void insertEmployee(Employee emp) throws SQLException {
setEmployee(emp);
PreparedStatement pr = conn.prepareStatement("INSERT INTO employees "
+ "(nickname,name,surname,password_emp) "
+ "VALUES (?,?,?,?)", PreparedStatement.RETURN_GENERATED_KEYS);
pr.setString(1, employee.getNickname());
pr.setString(2, employee.getName());
pr.setString(3, employee.getSurname());
pr.setString(4, employee.getPassword());
pr.executeUpdate();
ResultSet rs = pr.getGeneratedKeys();
while (rs.next()) {
employee.setId_employee(rs.getInt(1));
}
}
/**
* Delete an employee from database
* #param id
* #throws SQLException
*/
public void deleteEmployee(int id) throws SQLException {
PreparedStatement pr = conn.prepareStatement("DELETE FROM employees WHERE id_employee=?");
pr.setInt(1, id);
pr.executeUpdate();
}
}
To be more specific, we would like to create Runnable in methods and then add it to thread pool, but then, we would be able to get returns back.
Sounds like you want to submit Callable tasks (not Runnable) to a thread pool. When you submit a Callable<T> task to an ExecutorService, you get back a Future<T> object that you can use at a later time to wait for the result of the task.
You may want to do something like below. Your insertEmployee method will be called from call method.
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.concurrent.Callable;
public class EmployeeDTO implements Callable<String> {
private Employee employee;
private Connection conn;
private int id_employee;
/**
* Database connection
* #throws ClassNotFoundException
* #throws SQLException
*/
public EmployeeDTO() throws ClassNotFoundException, SQLException {
DatabaseConnection dbcon = new DatabaseConnection();
conn = dbcon.getConnection();
}
public EmployeeDTO(Employee employee) throws ClassNotFoundException, SQLException {
this.employee = employee;
DatabaseConnection dbcon = new DatabaseConnection();
conn = dbcon.getConnection();
}
/**
* Insert new Employee into database and sets it's id
* #param emp
* #throws SQLException
*/
public void insertEmployee(Employee emp) throws SQLException {
setEmployee(emp);
PreparedStatement pr = conn.prepareStatement("INSERT INTO employees "
+ "(nickname,name,surname,password_emp) "
+ "VALUES (?,?,?,?)", PreparedStatement.RETURN_GENERATED_KEYS);
pr.setString(1, employee.getNickname());
pr.setString(2, employee.getName());
pr.setString(3, employee.getSurname());
pr.setString(4, employee.getPassword());
pr.executeUpdate();
ResultSet rs = pr.getGeneratedKeys();
while (rs.next()) {
employee.setId_employee(rs.getInt(1));
}
}
/**
* Delete an employee from database
* #param id
* #throws SQLException
*/
public void deleteEmployee(int id) throws SQLException {
PreparedStatement pr = conn.prepareStatement("DELETE FROM employees WHERE id_employee=?");
pr.setInt(1, id);
pr.executeUpdate();
}
/**
* Computes a result, or throws an exception if unable to do so.
*
* #return computed result
* #throws Exception if unable to compute a result
*/
public String call() throws Exception {
insertEmployee(employee);
return "SUCCESS";
}
}
In other class you can use the ExecutorService like below
try{
Set<Callable<String>> callables = new HashSet<Callable<String>>();
EmployeeDTO employee = new EmployeeDTO(emp);
callables.add(employee);
ExecutorService executorService = Executors.newFixedThreadPool(1);
List<Future<String>> futures = executorService.invokeAll(callables);
}catch (ExecutionException eEx) {
eEx.getMessage();
}finally{
executorService.shutdown();
}

how to insert data from textboxes into mysql database in java-netbeans

I am new to programming and i am trying to make an small Java swing application using netbeans IDE and i have designed the Form and created an table too i used the following code to insert data into database from the form but i am getting many errors please help me to correct this code:
import java.sql.*;
public class db
{
static final String JDBC_DRIVER="com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/userdb";
static final String USER="root";
static final String PASS="toor";
Connection conn = null;
Statement stmt = null;
static final String d_unit=jTextField2.getText();
static final String d_name=jTextField3.getText();
static final String d_dob=jDateChooser2.getText();
//static final String d_gender="gender";
static final String d_age=jTextField4.getText();
static final String d_doorno=jTextField5.getText();
static final String d_street=jTextField6.getText();
static final String d_vc=jTextField7.getText();
static final String d_district=jTextField8.getText();
static final String d_pin=jTextField9.getText();
static final String d_phone=jTextField10.getText();
static final String d_mail=jTextField11.getText();
static final String d_occupations=jTextField12.getText();
try
{
Class.forName("com.mysql.jdbc.Driver");
conn=DriverManager.getConnection(DB_URL,USER,PASS);
stmt = conn.createStatement();
stmt.executeUpdate("insert into donors (unit,name,dob,age,doorno,street,vc,district,pin,phone,mail,occupation) values('"+d_unit+"','"+d_name+"','"+d_dob+"','"+d_age+"','"+d_doorno+"','"+d_street+"','"+d_vc+"','"+d_district+"','"+d_pin+"','"+d_phone+"','"+d_mail+"','"+d_occupations+"')");
JOptionPane.showMessageDialog(null,"Inserted Successfully!");
}
catch(Exception e)
{ }
}
You may not use the final String because, then you can't modify these Strings, and the other code is correct, but i think you can use the ? in the line:
String sql="INSERT INTO ´donors´ (unit,name) VALUES (?,?)";
//put the rest of the sentence
try {
PreparedStatement pdt = cn.prepareStatement(sql);
pdt.setString(1, jTextField2.getText();
pdt.setString(2, jTextField3.getText();
//put the rest of the code
int n1=pdt.executeUpdate();
if(n1>0)
{
JOptionPane.showMessageDialog(null,"Inserted Successfully!");
}
}catch (SQLException ex) { }
Well, that's the largest way, but the most correct. I hope this helps.
private void btnSaveActionPerformed(java.awt.event.ActionEvent evt) {
String itemCode = txtItemCode.getText();
String itemName = txtItemName.getText();
String unitPrice = txtUnitPrice.getText();
String qty = txtQty.getText();
String query = "insert into items values ('"+itemCode+"','"+itemName+"','"+unitPrice+"','"+qty+"')";
System.out.println(query);
try {
Connection c = DBClass.getConnection();
Statement stmt = c.createStatement();
stmt.executeUpdate(query);
JOptionPane.showMessageDialog(this, "Saved");
} catch (Exception e) {
e.printStackTrace();
}
// DBClass
import java.sql.Connection;
import java.sql.DriverManager;
/**
*
* #author Nadun
*/
public class DBClass {
static private Connection connection;
public static Connection getConnection() throws Exception{
if(connection == null){
//JDBC
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/stock", "root", "123");
}
return connection;
}
}
Everything looks alright. Maybe the trouble is on your mysql database?
Check the data type of your row in mysql, if your data type in the current row is "int", then it should be like this
try
{
Class.forName("com.mysql.jdbc.Driver");
conn=DriverManager.getConnection(DB_URL,USER,PASS);
stmt = conn.createStatement();
stmt.executeUpdate("insert into donors (name, age) values('"+d_name+"',,'"+Integer.valueOf(d_age.getText().toString())+"')");
JOptionPane.showMessageDialog(null,"Inserted Successfully!");
}
catch(Exception e){ }
}
You should be careful with data types. If your mysql row is int type then in your java you should give it int time as well.
I guess your data type of "name" row is text that use string, and your data type of "age" row is int?
I check your code is giving a string value from your java to your int mysql row. that's the error.
So you should convert the string to the int first
Integer.valueOf(d_age.getText().toString());
try proceeding like this for simplicity and less error-prone
String sql = "INSERT INTO donors(unit,name,dob,age,doorno,street,vc,district,pin,phone,mail,occupation) VALUES(?,?,?,?,?,?,?,?,?,?,?,?)";
stmt.executeUpdate(sql);

Categories