MySQL searching for data using Java [closed] - java

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I have this code for searching in the MySQL data table by id, but when I run the program it is giving me this error (Output : "Column 'Mart' Not Found"). I'm using JTextFiled to ask the user to enter the id that want to search for.
public void actionPerformed(ActionEvent event) {
if(event.getSource()== btn) {
try {
Connection connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);
PreparedStatement st = connection.prepareStatement("Select ID,user_name_1,password FROM Admin Where ID = ?");
int id = Integer.parseInt(text.getText());
st.setInt(1, id);
ResultSet rs = st.executeQuery();
if(rs.next()==false) {
JOptionPane.showMessageDialog(null, "The ID Not Found!!");
}
else {
String user = rs.getString("user_name_1");
text2.setText(rs.getString(user));
String pass = rs.getString("password");
text3.setText(rs.getString(pass));
}
}
catch (Exception e) {
System.out.print(e.getMessage());
}
}
}

Check if your column names are the same as the ones in the Database
Check if your connection string is connecting to the correct database
Ensure Database Driver is added
Try this:
public class DatabaseClass {
private String url = "YOUR URL";
private String username = "YOUR USERNAME";
private String password = "YOUR PASSWORD";
private static DatabaseClass theDB = new DatabaseClass();
private Connection c;
private DatabaseClass() {
try {
Class.forName("com.mysql.jdbc.Driver");
c = DriverManager.getConnection(url, username, password);
} catch (Exception ex) {
System.out.println("Error Connection: " + ex);
}
}
public Connection getC() {
return this.c;
}
public static DatabaseClass getInstance() {
return theDB;
}
}
And then, the click event:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
try {
HashMap<Integer, String> data = new HashMap<>();
int id = Integer.parseInt(jTextField1.getText());
Connection c = DatabaseClass.getInstance().getC();
PreparedStatement s = c.prepareStatement("select * from yourTable where ID = ?");
s.setInt(1, id);
ResultSet theResult = s.executeQuery();
while (theResult.next()) {
int yourID = theResult.getInt("ID");
String yourData = theResult.getString("Email_Address");
data.put(yourID, yourData);
}
for (HashMap.Entry theEntry : data.entrySet()) {
jTextArea1.append(String.valueOf(theEntry.getKey()) + " " + theEntry.getValue() + "\n");
}
} catch (Exception ex) {
System.out.println("Error: " + ex);
}
}
Ideally this should work, but replace the query with your query and the connection string with yours.

Related

Is the MySQL procedure in this Minecraft plugin correct?

To get an idea of what the basic structure looks like, I downloaded a money system including MySQL from Spigot and looked at the code.
public static boolean playerExists(String uuid) {
try {
ResultSet rs = Simplecoinsystem.mysql.query("SELECT * FROM CoinData WHERE UUID= '" + uuid + "'");
if (rs.next())
return (rs.getString("UUID") != null);
return false;
} catch (SQLException e) {
e.printStackTrace();
return false;
}
}
public static void createPlayer(String uuid) {
if (!playerExists(uuid))
Simplecoinsystem.mysql.update("INSERT INTO CoinData (UUID, COINS) VALUES ('" + uuid +
"', '" + Simplecoinsystem.getInstance().getConfig().getInt("startcoins") + "');");
}
public static Integer getCoins(String uuid) {
Integer i = Integer.valueOf(0);
if (playerExists(uuid)) {
try {
ResultSet rs = Simplecoinsystem.mysql.query("SELECT * FROM CoinData WHERE UUID= '" + uuid + "'");
if (rs.next())
Integer.valueOf(rs.getInt("COINS"));
i = Integer.valueOf(rs.getInt("COINS"));
} catch (SQLException e) {
e.printStackTrace();
}
} else {
createPlayer(uuid);
}
return i;
}
public static void setCoins(String uuid, Integer coins) {
if (playerExists(uuid)) {
Simplecoinsystem.mysql.update("UPDATE CoinData SET COINS= '" + coins + "' WHERE UUID= '" + uuid + "';");
} else {
createPlayer(uuid);
}
}
Am I correct that it is actually impractical to create a new entry with the uuid of the non-existent player after each query of the coins if the player does not exist?
Wouldn't this make it possible to flood the database with thousands of unnecessary entries by issuing, for example, a "/money (player)" command as an evil player/admin?
Couldn't I just ask when entering the server if the uuid is already stored and if not, just enter it? This way there would only be entries from players who have already been on the server before. Whether this needs great server performance, I'm not sure.
This is my first own MySQL class.
public class MySQL {
private String host, database, user, password;
private int port;
private Connection con;
public MySQL(String host, int port, String database, String user, String password) {
this.host = host;
this.port = port;
this.database = database;
this.user = user;
this.password = password;
connect();
}
public void connect() {
try {
con = DriverManager.getConnection("jdbc:mysql://" + host + ":" + port + "/" + database + "?autoReconnect=true", user, password);
System.out.println("&cDie MySQL Verbindung wurde erfolgreich aufgebaut!");
} catch (SQLException e) {
e.printStackTrace();
}
}
public void disconnect() {
try {
if(this.con != null) {
this.con.close();
System.out.println("§cDie MySQL Verbindung wurde erfolgreich beendet!");
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void update(String query) {
try {
Statement st = con.createStatement();
st.executeUpdate(query);
st.close();
} catch (Exception e) {
e.printStackTrace();
connect();
}
}
public ResultSet qry(String query) {
ResultSet rs = null;
try {
Statement st = con.createStatement();
rs = st.executeQuery(query);
} catch (Exception e) {
e.printStackTrace();
connect();
}
return rs;
}
public Connection getConnection() {
return this.con;
}
}
Except for this part, both MySQL classes are built relatively the same.
This is the part that is in the MySQL class of the Spigot plugin.
Your code have multiple issues.
When the connection will be closed, next time you will have an error. In your Mysql class, I suggest you to do:
public Connection getConnection() {
if(con == null || con.isClosed())
connect();
return con;
}
Then, use it in all method like getConnection().prepareStatement().
You can be attacked with SQL Injection. To fix this, try to do something like:
PreparedStatement st = con.prepareStatement("SELECT * FROM CoinData WHERE UUID = ?");
st.setString(1, uuid.toString()); // Yes it start at 1 !!
st.executeUpdate();
With this, even with all values, you can't be attacked with injections.
You will have an error while getting coins:
if (rs.next()) // go to good line
Integer.valueOf(rs.getInt("COINS")); // useless convertion
i = Integer.valueOf(rs.getInt("COINS")); // error if no line.
You can just do:
if(rs.next())
i = rs.getInt("COINS");
If the column "UUID" is unique, you will not have duplicated lines.
Finally, about performance, it's better to do it one time: at login, instead of all time. You can also create an object stored in an hashmap to easier access to it, without using SQL, like that:
public static HashMap<UUID, Integer> coinsByPlayer = new HashMap<>();
OR:
public static HashMap<UUID, MyObject> coinsByPlayer = new HashMap<>();
public class MyObject {
private int coins = 0;
public MyObject(UUID uuid) {
// make SQL request to get data
}
public int getCoins() {
return coins;
}
public void setCoins(int next){
coins = next;
// here make "UPDATE" sql query
}
}
What do you say? Is it ok with the try/catch function? #Elikill58
public Connection getConnection() {
try {
if(con == null || con.isClosed()) {
connect();
}
} catch (SQLException e) {
e.printStackTrace();
}
return con;
}
edit:
public Connection getConnection_one() throws SQLException {
if(con == null || con.isClosed()) {
connect();
return con;
} else {
return con;
}
}

How to search a database to verify it exists?

I have been working with a java database for this class I'm just trying to search and see if the entry with the same name the user inputs exists. It used to work but for some, it keeps saying it doesn't exist in the database even if it does. If someone could give me a solution it would be greatly appreciated.
private void btnSearchActionPerformed(java.awt.event.ActionEvent evt) {
name = txtSearch.getText();
sr.setSearch(name);
try {
String url = "jdbc:derby://localhost:1527/Cookbook";
Connection conn = DriverManager.getConnection(url);
String sql = "SELECT * from RECIPES where NAME = ?";
PreparedStatement pst = conn.prepareStatement(sql);
pst.setString(1, name);
ResultSet rs = pst.executeQuery();
boolean found = false;
while (rs.next()) {
if (rs.getString(1).equalsIgnoreCase(name)) {
JOptionPane.showMessageDialog(null, "Found " + name);
found = true;
break;
}
}
if (found) {
this.dispose();
modifyingRecipe m = new modifyingRecipe();
m.setVisible(true);
} else {
JOptionPane.showMessageDialog(null, "Item Not Found!");
}
} catch (SQLException ex) {
Logger.getLogger(CookbookApp.class.getName()).log(Level.SEVERE, null, ex);
}
}

Java - a GUI update button

i am trying to making an update button in my GUI form that can be edit a record in my DB but i missing something that i hope someone to help me
this the code of update method:
public int updateUser(Login user) //int
{
DatabaseConnection dbconn = new DatabaseConnection();
Connection conn = dbconn.getConn();
int rows = 0;
try
{
String sql = "UPDATE LOGIN set USER_NAME = ? , PASSWORD = ? , PRIVILEGE_ID = ?";
PreparedStatement pStm = conn.prepareStatement(sql);
//fill SQL parameters from user: //
pStm.setString(1, user.getUserName());
pStm.setString(2, user.getPassword());
pStm.setInt(3, user.getPrivilegeId());
rows =
pStm.executeUpdate();
}
catch (SQLException ex) {
System.out.println("SQLException: " + ex.getMessage());
}
finally
{
try {
conn.close();
} catch (SQLException ex) {
System.out.println("SQLException: " + ex.getMessage());;
}
}
return rows;
}
code in java swing for update button:
private void updateUserLayerActionPerformed(java.awt.event.ActionEvent evt) {
// 1-get data from user and check it: //
String _name = nameLayer.getText().trim();
String _paswrd = passLayer.getText().trim();
String _prvName = privLayer.getSelectedItem().toString();
//get Privilege_Id from DB:
PrivilegeHandeler prvHndler = new PrivilegeHandeler();
int prvId = prvHndler.getPrivilegeByName(_prvName);
if(_name.length() >0 && _paswrd.length() >0 && prvId> 0)
{
Login user = new Login();
user.setUserName(_name);
user.setPassword(_paswrd);
user.setPrivilegeId(prvId);
//update User: //
loginHandeler loghndlr = new loginHandeler();
int rows =
loghndlr.updateUser(user);
if (rows >0)
{
usrFormErorr.setText("user has been added successfully :)");
nameLayer.setText("");
passLayer.setText("");
privLayer.setSelectedIndex(0);
}
else
{
usrFormErorr.setText("updated failed, try again");
}
}
else
{
usrFormErorr.setText("please, fill the required fields first");
}
}
My problem is this:
1-i am trying to enter an info to edit then update but always get an error updated failed, try again that i made it to get a message when there is a problem
Kindly help. A working code would be very highly appreciated. Thanks in advance.

How to use an MySQL database to authenticate a user?

I'm trying to authenticate a user (login) in java using MySQL database. I want to be able to do this in the console. This is what i have so far: My main class-
import java.util.Scanner;
public class main {
public static void main(String args[]){
if (args.length < 2)
return;
login meth = new login();
Scanner in = new Scanner(System.in);
String username;
String password;
System.out.println("");
System.out.println("Username: ");
username = in.next();
System.out.println("2. Account Holder");
password = in.next();
System.out.println("");
meth.loginDetails(username, password);
login checker = new login();
boolean rc = checker.loginDetails(args[0], args[1]);
System.out.println("The result is: " + Boolean.toString(rc));
in.close();
}
}
And this is my class where i attempt to connect to the database and query it.
import java.sql.*;
public class login {
public void databaseConnection(){ //swapping index a and index b around
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = null;
conn = DriverManager.getConnection("jdbc:mysql://localhost/loginTest","root", "");
System.out.println("Database is connected !");
conn.close();
}
catch(Exception e){
System.out.println("Do not connect to DB - Error:"+e);
}
}
static final String CONN_URL = "jdbc:mysql://localhost/loginTest";
static final String DB_USER = "root";
static final String DB_PASSWORD = "";
public boolean loginDetails(String accountNumber, String password){
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
boolean passwdOK = false;
try {
// Establish the connection.
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
con = DriverManager.getConnection(CONN_URL, DB_USER, DB_PASSWORD);
// Create and execute an SQL statement
String sqlst = "SELECT Password FROM customer " +
" WHERE Account Number = '" + accountNumber + "'";
stmt = con.createStatement();
rs = stmt.executeQuery(sqlst);
// Check the return data
if (rs.next()) {
String passwdSaved = rs.getString(1).trim();
if (passwdSaved.equals(password.trim()))
passwdOK = true;
}
rs.close();
stmt.close();
}
catch (Exception e) {
e.printStackTrace();
}
finally {
if (con != null) try { con.close(); } catch(Exception e) {}
}
return passwdOK;
}
}
My database is called Customer and the separate columns are called Account Number, Password.
At the moment when i run the program it gets instantly terminated. Without showing any of the print lines.
So my question is how do i get a result true or false, that the user name and password is a match. And if it was false, let them retry and if its true load a switch menu?
First of all change
boolean rc = checker.loginDetails(args[0], args[1]);
to
boolean rc = checker.loginDetails(username, password);
If you are not running this program with arguments then args[0] and args[1] will throw ArrayIndexOutOfBoundException

Inserting data into a database - org.h2.jdbc.JdbcSQLException: Column count does not match; SQL statement:

I've been trying to save values into a database called "CLIENT".
The database is created via this code:
package Database;
//STEP 1. Import required packages
import java.sql.*;
public class JDBCExampleCreateTables {
// JDBC driver name and database URL
private static String JDBC_DRIVER = "org.h2.Driver";
private static String DB_URL = "jdbc:h2:file:C:/WAKILI/WAKILIdb";
// Database credentials
private static String USER = "sa";
private static String PASS = "";
public static void main (String[] args) {
Connection conn = null;
Statement stmt = null;
try {
//STEP 2: Register JDBC driver
Class.forName(JDBC_DRIVER);
//STEP 3: Open a connection
System.out.println("Connecting to a selected database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
System.out.println("Connected database successfully...");
//STEP 4: Execute a query
System.out.println("Creating table in given database...");
stmt = conn.createStatement();
String sql = "CREATE TABLE CLIENT " +
"(ID INT UNSIGNED NOT NULL AUTO_INCREMENT, " +
" fullNames VARCHAR(255), " +
" iDNumber VARCHAR(255), " +
" pINNumber VARCHAR(255), " +
" passportNumber VARCHAR(255), " +
" postOfficeBoxNumber VARCHAR(255), " +
" postalCode VARCHAR(255), " +
" telephoneNumberLandline VARCHAR(255), " +
" telephoneNumberMobile VARCHAR(255), " +
" CARD VARCHAR(255)) ";
stmt.executeUpdate(sql);
System.out.println("Created table in given database...");
} catch (SQLException se) {
//Handle errors for JDBC
se.printStackTrace();
} catch (Exception e) {
// Handle errors for Class.forName
e.printStackTrace();
} finally {
// finally block used to close resources
try {
if (stmt!=null)
conn.close();
} catch(SQLException se) {
} // do nothing
try {
if (conn!=null)
conn.close();
} catch (SQLException se) {
se.printStackTrace();
} // end finally try
} // end try
System.out.println("Goodbye!");
} // end main
} // end
The class that I'm trying to have save into the database is:
package Database;
//STEP 1. Import required packages
import java.sql.*;
public class JDBCExampleInsertRecords {
public final String values;
public final String table;
public JDBCExampleInsertRecords (String values, String table)
{
this.values = values;
this.table = table;
}
// JDBC driver name and database URL
private static String JDBC_DRIVER = "org.h2.Driver";
private static String DB_URL = "jdbc:h2:file:C:/WAKILI/WAKILIdb";
// Database credentials
private static String USER = "sa";
private static String PASS = "";
public static void main () {
Connection conn = null;
Statement stmt = null;
try {
//STEP 2: Register JDBC driver
Class.forName(getJDBC_DRIVER());
//STEP 3: Open a connection
System.out.println("Connecting to a selected database...");
conn = DriverManager.getConnection(getDB_URL(), getUSER(), getPASS());
System.out.println("Connected database successfully...");
//STEP 4: Execute a query
System.out.println("Inserting records into the table...");
stmt = conn.createStatement();
String sql = "INSERT INTO CLIENT " + "VALUES ((values))";
stmt.executeUpdate(sql);
System.out.println("Inserted records into the table...");
} catch (SQLException se) {
//Handle errors for JDBC
se.printStackTrace();
} catch (Exception e) {
//Handle errors for Class.forName
e.printStackTrace();
} finally {
//finally block used to close resources
try {
if (stmt != null)
conn.close();
} catch (SQLException se) {
} // do nothing
try {
if (conn!=null)
conn.close();
} catch (SQLException se) {
se.printStackTrace();
} //end finally try
} //end try
System.out.println("Goodbye!");
} //end main
/**
* #return the JDBC_DRIVER
*/
public static String getJDBC_DRIVER() {
return JDBC_DRIVER;
}
/**
* #param aJDBC_DRIVER the JDBC_DRIVER to set
*/
public static void setJDBC_DRIVER(String aJDBC_DRIVER) {
JDBC_DRIVER = aJDBC_DRIVER;
}
/**
* #return the DB_URL
*/
public static String getDB_URL() {
return DB_URL;
}
/**
* #param aDB_URL the DB_URL to set
*/
public static void setDB_URL(String aDB_URL) {
DB_URL = aDB_URL;
}
/**
* #return the USER
*/
public static String getUSER() {
return USER;
}
/**
* #param aUSER the USER to set
*/
public static void setUSER(String aUSER) {
USER = aUSER;
}
/**
* #return the PASS
*/
public static String getPASS() {
return PASS;
}
/**
* #param aPASS the PASS to set
*/
public static void setPASS(String aPASS) {
PASS = aPASS;
}
} //end
The code that gets the values is in a Class called "AddNewClient" and is as follows:
public String getValues () {
String fullNames = fullNamesJTextField.getText();
String iDNumber = identificationNumberJTextField.getText();
String pINNumber = pINNumberJTextField.getText();
String passportNumber = passportNumberJTextField.getText();
String postOfficeBoxNumber = postOfficeBoxNumberJTextField.getText();
String postalCode = postalCodeJTextField.getText();
String telephoneNumberLandline = telephoneNumberLandlineJTextField.getText();
String telephoneNumberMobile = telephoneNumberMobileJTextField.getText();
List<String> client = new ArrayList<String>();
client.add(fullNames);
client.add(iDNumber);
client.add(pINNumber);
client.add(passportNumber);
client.add(postOfficeBoxNumber);
client.add(postalCode);
client.add(telephoneNumberLandline);
client.add(telephoneNumberMobile);
StringBuilder builder = new StringBuilder();
String listStringClient = "";
for (String s : client)
{
listStringClient += "NULL" + "'" + s + "'" + ",";
}
return listStringClient;
}
I get an error message:
run:
Connecting to a selected database...
Connected database successfully...
Inserting records into the table...
org.h2.jdbc.JdbcSQLException: Column count does not match; SQL statement:
I've been at this for the past two days to no success whatsoever. I will be very, very very greatful to anyone who would come to my rescue. Thank you.
This is where one problem is:
String sql = "INSERT INTO CLIENT " + "VALUES ((values))";
stmt.executeUpdate(sql);
Values should be the getValues() method, instead of just a string, so
String sql = "INSERT INTO CLIENT VALUES (" + getValues() + ")";
Additionally, since you do not specify which columns, it is assumed that all columns are being entered in the values. If CARD does not have a default value in your SQL database, and if it cannot be NULL, you're going to have a problem.
Finally, this is a little strange:
for (String s : client)
{
listStringClient += "NULL" + "'" + s + "'" + ",";
}
You'll want the values, not 'NULL', so it should be
for (String s : client)
{
listStringClient += "'" + s + "'" + ",";
}
And finally, the way you're doing it, you're going to have an extra comma at the end (ex: 'value1','value2','value3',)
Clip the final comma:
return listStringClient.substring(0, listStringClient.size() - 1);
Granted, there's a better way to do the for loop where you do not have that extra comma.
End the end, the sql String should look like this:
"INSERT INTO CLIENT VALUES('value1','value2','value3','value4','value5','value6')"
Do a System.out.println(sql) and see what the String statement is that you're trying to execute. You'll see the error then.
Here's a better way to build your values string without the comma issue:
Iterator<String> iter = client.iterator();
StringBuilder sb = new StringBuilder();
while (iter.hasNext()) {
sb.append("'").append(iter.next()).append("'");
if (iter.hasNext())
sb.append(",");
}
return sb.toString();
You forget to mention the value for CARD column. If you dont want to set any value there, just pass ' '.
Your for loop should be like this
for (String s : client)
{
listStringClient += "NULL" + "'" + s + "'" + ",";//GIVES YOU ERROR BECAUSE AT THE END OF
} // FOR LOOP IT HAS , IN THE END OF STRING.
listStringClient+="' '";//This is for CARD COLUMN.
You do not pass any value in your statement. Following code is static, it does not have parameters:
INSERT INTO CLIENT " + "VALUES ((values))
It is nonsense SQL command: INSERT INTO CLIENT VALUES ((values)). You wanted express
String sql = "INSERT INTO CLIENT VALUES " + getValues()";
I prefer to use PreparedStatement, as it is safe and it will escape dangerous characters:
String sql = "INSERT INTO PRODUCT VALUES(?,?,?,?,?,?,?,?,?,?)";
PreparedStatement prest = con.prepareStatement(sql);
prest.setString(1, "asdf");
prest.setInt(2, 2009);
// etc
int count = prest.executeUpdate();
I think instead of :
String sql = "INSERT INTO CLIENT " + "VALUES ((values))";
You want something like :
String sql = "INSERT INTO CLIENT " + "VALUES ("+getValues()+")";
Also the implementation of getValues is kind of strange :
for (String s : client)
{
listStringClient += "NULL" + "'" + s + "'" + ",";
}
Probably it could be :
for (String s : client)
{
listStringClient += "'" + s + "',"
}
listStringClient += "NULL";
I can't thank you all enough for the amazing answers. I put the various ideas and came up with this solution to my problem.
My working answer to my Question above takes ideas from Leos Literak, abmitchell, Vimal Bera and Grisha's answers.
The database is created via this code:
package Database;
//STEP 1. Import required packages
import java.sql.*;
public class JDBCExampleCreateTables {
// JDBC driver name and database URL
private static String JDBC_DRIVER = "org.h2.Driver";
private static String DB_URL = "jdbc:h2:file:C:/WAKILI/WAKILIdb";
// Database credentials
private static String USER = "sa";
private static String PASS = "";
public static void main (String[] args) {
Connection conn = null;
Statement stmt = null;
try {
//STEP 2: Register JDBC driver
Class.forName(JDBC_DRIVER);
//STEP 3: Open a connection
System.out.println("Connecting to a selected database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
System.out.println("Connected database successfully...");
//STEP 4: Execute a query
System.out.println("Creating table in given database...");
stmt = conn.createStatement();
String sql = "CREATE TABLE CLIENT " +
"(ID INT UNSIGNED NOT NULL AUTO_INCREMENT, " +
" fullNames VARCHAR(255), " +
" iDNumber VARCHAR(255), " +
" pINNumber VARCHAR(255), " +
" passportNumber VARCHAR(255), " +
" postOfficeBoxNumber VARCHAR(255), " +
" postalCode VARCHAR(255), " +
" telephoneNumberLandline VARCHAR(255), " +
" telephoneNumberMobile VARCHAR(255)) ";
stmt.executeUpdate(sql);
System.out.println("Created table in given database...");
} catch (SQLException se) {
//Handle errors for JDBC
se.printStackTrace();
} catch (Exception e) {
// Handle errors for Class.forName
e.printStackTrace();
} finally {
// finally block used to close resources
try {
if (stmt!=null)
conn.close();
} catch(SQLException se) {
} // do nothing
try {
if (conn!=null)
conn.close();
} catch (SQLException se) {
se.printStackTrace();
} // end finally try
} // end try
System.out.println("Goodbye!");
} // end main
} // end
The class that saves into the database is:
package Database;
//STEP 1. Import required packages
import java.sql.*;
public class JDBCExampleInsertRecords {
public static String values;
public final String table;
public JDBCExampleInsertRecords (String values, String table)
{
this.values = values;
this.table = table;
}
// JDBC driver name and database URL
private static String JDBC_DRIVER = "org.h2.Driver";
private static String DB_URL = "jdbc:h2:file:C:/WAKILI/WAKILIdb";
// Database credentials
private static String USER = "sa";
private static String PASS = "";
public static void main () {
Connection conn = null;
Statement stmt = null;
try {
//STEP 2: Register JDBC driver
Class.forName(getJDBC_DRIVER());
//STEP 3: Open a connection
System.out.println("Connecting to a selected database...");
conn = DriverManager.getConnection(getDB_URL(), getUSER(), getPASS());
System.out.println("Connected database successfully...");
//STEP 4: Execute a query
System.out.println("Inserting records into the table...");
stmt = conn.createStatement();
String sql = "INSERT INTO CLIENT VALUES (NULL, " + (values) + ")";
stmt.executeUpdate(sql);
System.out.println("Inserted records into the table...");
} catch (SQLException se) {
//Handle errors for JDBC
se.printStackTrace();
} catch (Exception e) {
//Handle errors for Class.forName
e.printStackTrace();
} finally {
//finally block used to close resources
try {
if (stmt != null)
conn.close();
} catch (SQLException se) {
} // do nothing
try {
if (conn!=null)
conn.close();
} catch (SQLException se) {
se.printStackTrace();
} //end finally try
} //end try
System.out.println("Goodbye!");
} //end main
/**
* #return the JDBC_DRIVER
*/
public static String getJDBC_DRIVER() {
return JDBC_DRIVER;
}
/**
* #param aJDBC_DRIVER the JDBC_DRIVER to set
*/
public static void setJDBC_DRIVER(String aJDBC_DRIVER) {
JDBC_DRIVER = aJDBC_DRIVER;
}
/**
* #return the DB_URL
*/
public static String getDB_URL() {
return DB_URL;
}
/**
* #param aDB_URL the DB_URL to set
*/
public static void setDB_URL(String aDB_URL) {
DB_URL = aDB_URL;
}
/**
* #return the USER
*/
public static String getUSER() {
return USER;
}
/**
* #param aUSER the USER to set
*/
public static void setUSER(String aUSER) {
USER = aUSER;
}
/**
* #return the PASS
*/
public static String getPASS() {
return PASS;
}
/**
* #param aPASS the PASS to set
*/
public static void setPASS(String aPASS) {
PASS = aPASS;
}
} //end
The code that gets the values is in a Class called "AddNewClient" and is as follows:
public String getValues () {
String fullNames = fullNamesJTextField.getText();
String iDNumber = identificationNumberJTextField.getText();
String pINNumber = pINNumberJTextField.getText();
String passportNumber = passportNumberJTextField.getText();
String postOfficeBoxNumber = postOfficeBoxNumberJTextField.getText();
String postalCode = postalCodeJTextField.getText();
String telephoneNumberLandline = telephoneNumberLandlineJTextField.getText();
String telephoneNumberMobile = telephoneNumberMobileJTextField.getText();
List<String> client = new ArrayList<String>();
client.add(fullNames);
client.add(iDNumber);
client.add(pINNumber);
client.add(passportNumber);
client.add(postOfficeBoxNumber);
client.add(postalCode);
client.add(telephoneNumberLandline);
client.add(telephoneNumberMobile);
Iterator<String> iter = client.iterator();
StringBuilder sb = new StringBuilder();
while (iter.hasNext()) {
sb.append("'").append(iter.next()).append("'");
if (iter.hasNext())
sb.append(",");
}
return sb.toString();
}

Categories