JAVA 1.7 and Mysql 5.7 connection - java

I have Java jdk1.7xxx installed and a MySQL database v5.7 too.
My database is named "mydb".
I access it from the mysql console.
However when I try to access it from my java program it makes an error "source of data unknown, or pilot name not specified". So I am missing some pilot/extra file I guess. But I did import java.sql.* at the beginning of my program..
import javax.swing.*;
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.event.*;
import java.sql.SQLException;
import java.util.ArrayList;
import javax.swing.table.DefaultTableModel;
import javax.swing.*;
import java.sql.*;
import java.util.*;
public class DPIA_impacts extends JFrame {
// Labels
JLabel lb_title;
JTable tableau = null;
static JPanel p_global, p_title, p_center, p_south;
JScrollPane scroll=null;
JButton btn_Save, btn_Export;
//DefaultTableModel model;
ArrayList t1=new ArrayList();
ArrayList t2=new ArrayList();
ArrayList t3=new ArrayList();
public DPIA_impacts(){
//declarations
p_global = new JPanel();
p_title = new JPanel();
p_center = new JPanel();
p_south = new JPanel();
lb_title = new JLabel("DPIA meeting: fill the table !");
btn_Save = new JButton("Save");
btn_Export = new JButton("Export");
scroll = new JScrollPane();
// add tool tip text to the Save and Export buttons
btn_Save.setToolTipText("Save to the database Impacts table");
btn_Export.setToolTipText("Exports the contents of the Jtable to an Excel file");
// add Action Listener to the buttons
btn_Save.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
//Execute when button is pressed
System.out.println("You clicked the button SAVE");
String url = "jdbc:mysql://localhost/mydb";
String login = "root";
String passwd = "toor";
Connection cn = null;
Statement st = null;
try {
//chargement du driver
Class.forName("com.mysql.jdbc.Driver");
// Recup connexion
cn = DriverManager.getConnection(url, login, passwd);
// Creation d'un statement
st = cn.createStatement();
String sql = "SELECT * FROM impacts";
st.executeUpdate(sql);
//instruction.executeQuery(req);
} // Try
catch (SQLException ex)
{
System.out.println("Connexion à la base de données impossible");
ex.printStackTrace();
}
catch(ClassNotFoundException ex)
{
System.out.println("Pilote de connexion introuvable");
ex.printStackTrace();
//}//end catch
} finally {
try{
cn.close();
st.close();
} catch (SQLException sqle){
sqle.printStackTrace();
}
}
}});
btn_Export.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
//Execute when button is pressed
System.out.println("You clicked the button EXPORT");
}
});
//add the components to the righ panels
p_title.add(lb_title);
p_center.add(scroll);
p_south.add(btn_Save, BorderLayout.WEST);
p_south.add(btn_Export, BorderLayout.EAST);
String req = "SELECT * FROM impacts";
int i =0;
Connect resultat = new Connect(req,1,"BaseDeDonnees");
// connexion a la base de donnees
}//end constructor
public static void main(String args[]) {
//Create and set up the window.
DPIA_impacts f = new DPIA_impacts();
f.setTitle("DPIA: check the impacts");
//f = new JFrame("DPIA: Impacts");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Set up the content pane
f.getContentPane().setLayout(new BorderLayout());
f.getContentPane().add(p_title, BorderLayout.PAGE_START);
f.getContentPane().add(p_center, BorderLayout.CENTER);
f.getContentPane().add(p_south, BorderLayout.PAGE_END);
f.pack();
f.setSize(500, 300);
f.setVisible(true);
}//end main
}//end programm !
Adding the jar:

I think that in String url = "jdbc:mysql://localhost/mydb";
you forgot to write the port number.
try String url ="jdbc:mysql://127.0.0.1:3306/mydb";
UPDATE
Ok, just try this code and run it from Eclipse and not from cmd.
Also you use executeUpdate for INSERT. For SELECT you use executeQuery.
//Execute when button is pressed
System.out.println("You clicked the button SAVE");
String url = "jdbc:mysql://127.0.0.1:3306/mydb";
String login = "root";
String passwd = "toor";
Connection cn = null;
Statement st = null;
ResultSet rs = null;
System.out.println("Connecting to database..");
try {
cn = DriverManager.getConnection(url, login, passwd);
System.out.println("Database Connected");
st = cn.createStatement();
String sql = "SELECT * FROM impacts";
rs = st.executeQuery(sql);
while (rs.next()){
//do something
}
//instruction.executeQuery(req);
} // Try
catch (SQLException ex)
{
System.out.println("Connexion à la base de données impossible");
ex.printStackTrace();
}
finally {
try{
if (cn != null ){
cn.close();
}
if (st != null ){
st.close();
}
if (rs != null ){
rs.close();
}
} catch (SQLException sqle){
sqle.printStackTrace();
}
}

Related

Cannot login using Swing

I created a login GUI login form and tried to login if the username and password matches with that entered in the database. But, I am unable to login
I could not find any error in the code.
public class Login {
private JTextField nameTextField;
private JButton submitButton;
private JTextField passwordTextField;
private JLabel Message;
private JPanel LoginPanel;
public static void main(String[] args) {
JFrame frame=new JFrame("Login");
frame.setContentPane(new Login().LoginPanel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setSize(650,500);
frame.setVisible(true);
}
public Login() {
submitButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
Connection con = null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/java_db", "root", "");
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("select * from employee");
while (rs.next()) {
if (rs.getString("name").equals(nameTextField.getText()) && rs.getString("password").equals(passwordTextField.getText())) {
Message.setText("Login Success");
}
else {
Message.setText("Failed");
}
}
con.close();
} catch (SQLException e1) {
e1.printStackTrace();
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
}
}
});
}}
If the password and username matches, I want the application to show the message "Login Success"
Currently you're scanning the whole table and in fact check the username/password of the last element in the DB.
I would simply get the (unique) element corresponding to the username entered and verify the password.
Something like this:
PreparedStatement st = con.prepareStatement("SELECT password FROM employee WHERE name = ?");
st.setString(1, nameTextField.getText().trim());
ResultSet rs = st.executeQuery();
if (rs.next() && rs.getString(1).equals(passwordTextField.getText()))
Message.setText("Login Success");
else
Message.setText("Failed");
rs.close();
con.close();

Deleting data in table (SQLite) through java (Eclipse)

as the title suggests, ive been trying to delete data in a table in my SQLite through the use of a button. I have been able to make it work on another class, but i cant seem to make it work on this specific class which i will show you.
the button is called btnDelete, and the method that loads the database and deletes it is called delete_account.
Button btnDelete = new JButton("Delete Account");
btnDelete.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
delete_account();
}
});
public void delete_account(){
try { //start or try
//1)create a connection variable
Connection con;
//2)create an instance of the database class
Database db=new Database();
//3)pass the connection from DB to con
con=db.open_connection();
//4)create a statement variable to prepare the SQL
Statement statement=con.createStatement();
//5)create a query to insert the records
String query="DELETE FROM tblUsers WHERE userID="+ userid +"";
//6) execute the SQL code
if(statement.executeUpdate(query)==1) { //query was successful
JOptionPane.showMessageDialog(null, "Account successfully deleted!");
//clear the inputs
new MainInterface(user);
frmAccountSett.dispose();
}
}//end of try
catch (Exception e){//start of catch
//display the error
JOptionPane.showMessageDialog(null,e.getMessage());
}//end of catch
}//end of save_recipe()
Here's the whole code in the class just in case it is needed:
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.JPasswordField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.sql.*;
public class AccSettings {
private JFrame frmAccountSett;
private JTextField txtFullname;
private JTextField txtUsername;
private JPasswordField txtPassword;
private int userid;
private String user;
/**
* Create the application.
*/
public AccSettings(String username) {
user=username;
//userid = id;
initialize();
edit_account();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frmAccountSett = new JFrame();
frmAccountSett.setTitle("Account Settings");
frmAccountSett.setBounds(100, 100, 450, 300);
frmAccountSett.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmAccountSett.getContentPane().setLayout(null);
JLabel lblUsername = new JLabel("Edit Username:");
lblUsername.setBounds(85, 62, 103, 14);
frmAccountSett.getContentPane().add(lblUsername);
txtUsername = new JTextField();
txtUsername.setBounds(229, 59, 137, 20);
frmAccountSett.getContentPane().add(txtUsername);
txtUsername.setColumns(10);
txtPassword = new JPasswordField();
txtPassword.setBounds(229, 90, 137, 20);
frmAccountSett.getContentPane().add(txtPassword);
JButton btnConfirm = new JButton("Confirm Changes");
btnConfirm.setBounds(146, 164, 137, 29);
frmAccountSett.getContentPane().add(btnConfirm);
JLabel lblPassword = new JLabel("Edit Password:");
lblPassword.setBounds(85, 93, 103, 14);
frmAccountSett.getContentPane().add(lblPassword);
frmAccountSett.setVisible(true);
JButton btnDelete = new JButton("Delete Account");
btnDelete.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
delete_account();
}
});
btnDelete.setBounds(299, 227, 125, 23);
frmAccountSett.getContentPane().add(btnDelete);
JButton btnBack = new JButton("<< Back");
btnBack.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
frmAccountSett.dispose();
}
});
btnBack.setBounds(10, 227, 103, 23);
frmAccountSett.getContentPane().add(btnBack);
JLabel lblFullname = new JLabel("Edit Fullname:");
lblFullname.setBounds(85, 31, 103, 14);
frmAccountSett.getContentPane().add(lblFullname);
txtFullname = new JTextField();
txtFullname.setColumns(10);
txtFullname.setBounds(229, 28, 137, 20);
frmAccountSett.getContentPane().add(txtFullname);
btnConfirm.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
update_account();
}
});
}
public void delete_account(){
try { //start or try
//1)create a connection variable
Connection con;
//2)create an instance of the database class
Database db=new Database();
//3)pass the connection from DB to con
con=db.open_connection();
//4)create a statement variable to prepare the SQL
Statement statement=con.createStatement();
//5)create a query to insert the records
String query="DELETE FROM tblUsers WHERE userID="+ userid +"";
//6) execute the SQL code
if(statement.executeUpdate(query)==1) { //query was successful
JOptionPane.showMessageDialog(null, "Account successfully deleted!");
//clear the inputs
new MainInterface(user);
frmAccountSett.dispose();
}
}//end of try
catch (Exception e){//start of catch
//display the error
JOptionPane.showMessageDialog(null,e.getMessage());
}//end of catch
}//end of save_recipe()
public void update_account(){
try { //start or try
//1)create a connection variable
Connection con;
//2)create an instance of the database class
Database db=new Database();
//3)pass the connection from DB to con
con=db.open_connection();
//4)create a statement variable to prepare the SQL
Statement statement=con.createStatement();
//5)create a query to insert the records
#SuppressWarnings("deprecation")
String query="UPDATE tblUsers SET fullname='" + txtFullname.getText()+"',"
+ "username='" + txtUsername.getText()+"',"
+ "password='" + txtPassword.getText()+"'"
+ "WHERE userID="+ userid +"";
//6) execute the SQL code
if(statement.executeUpdate(query)==1) { //query was successful
JOptionPane.showMessageDialog(null, "Reference successfully updated!");
//clear the inputs
new MainInterface(user);
frmAccountSett.dispose();
}
}//end of try
catch (Exception e){//start of catch
//display the error
JOptionPane.showMessageDialog(null,e.getMessage());
}//end of catch
}//end of save_recipe()
//load the results
public void edit_account()
{
try {
Connection con; //create a variable for con
Database db = new Database(); //create an instance of database class
con = db.open_connection(); //set con as connection form database class
Statement st;
st = con.createStatement();
//create a statement variable
//create the query that will search the table based on similar terms
String query = "SELECT * FROM tblUsers WHERE userID=" + userid+ "";
//get the resultset of the query (rows)
ResultSet rs = st.executeQuery(query);
if (rs.next())
{
do{
txtFullname.setText(rs.getString(2));
txtUsername.setText(rs.getString(3));
txtPassword.setText(rs.getString(4));
}
while(rs.next());
}
/*
else {
JOptionPane.showMessageDialog(null, "Edit failed");
}
*/
}
catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I believe the problem stems mostly from userID which zephyr has stated. I followed a code from another class(frmEditRef), but that class uses a JScrollPane, which when called from another class (frmMainInterface) looks like this:
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
int x = table.getSelectedRow(); //get the current row
int ans = JOptionPane.showConfirmDialog(null, "Do you want to edit this record?");
if (ans == 0) {
//proceed to edit the transaction
//get the id
String id = String.valueOf(model.getValueAt(x, 0));
new EditRef(user,Integer.valueOf(id));
frmUserRef.dispose();
}
}
});
The class im trying to work with does not use JScrollPane. Therefore the coding to it would be different. Here's how it looks like from frmMainInterface:
btnAccountSett.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
String id = ;
new AccSettings(user,Integer.valueOf(id));
}
});
As you can see, i have no idea what to put in after the "String id =".
I hope this explanation can get through you guys. I myself am having difficulty trying to explain something i dont even fully understand.

embed MS Access database with runnable jar

So my aim is to make a runnable jar. I've made a program using swings which uses MS Access database to fetch records. So, I've used an absolute path to refer to the database for connection.
Now, I intend to distribute this runnable jar to other people as well. So I guess the best option would be to embed the MS Access database as well in the jar file. But I don't know how to do that. Where should I keep the database in my Project Explorer ? Should I use a relative path etc. Any form of help would be appreciable.
I've found many tutorials for using Derby database that would implement the same but none pertaining to Ms Access database. Suggestions are welcome !
This is my code:-
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
import java.util.Vector;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
public class r_search extends JFrame implements ActionListener {
JFrame frame1;
JLabel l0, l1, l2;
JComboBox c1;
JButton b1;
Connection con;
ResultSet rs, rs1;
Statement st, st1;
PreparedStatement pst;
String ids;
static JTable table;
String[] columnNames = {"SECTION NAME", "REPORT NAME", "CONTACT", "LINK"};
String from;
r_search() {
l0 = new JLabel("Fetching Search Results...");
l0.setForeground(Color.blue);
l0.setFont(new Font("Serif", Font.BOLD, 20));
l1 = new JLabel("Search");
b1 = new JButton("submit");
l0.setBounds(100, 50, 350, 40);
l1.setBounds(75, 110, 75, 20);
b1.setBounds(150, 150, 150, 20);
b1.addActionListener(this);
setTitle("Search Executive Reports :) ");
setLayout(null);
//setVisible(true);
setSize(500, 500);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
add(l0);
add(l1);;
add(b1);
try {
Vector v = new Vector();
String url="jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=" + "C:\\users\\ppreeti\\executive_db.accdb";
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection(url,"","");
/*con = DriverManager.getConnection("jdbc:oracle:thin:#mcndesktop07:1521:xe", "sandeep", "welcome");*/
st = con.createStatement();
rs = st.executeQuery("select index_name from Index1");
// Vector v = new Vector();
while (rs.next()) {
ids = rs.getString(1);
v.add(ids);
}
c1 = new JComboBox(v);
c1.setBounds(150, 110, 150, 20);
add(c1);
st.close();
rs.close();
} catch (Exception e) {
}
setVisible(true);
}
public void actionPerformed(ActionEvent ae) {
if (ae.getSource() == b1) {
showTableData();
}
}
public void showTableData() {
frame1 = new JFrame("Database Search Result");
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame1.setLayout(new BorderLayout());
//TableModel tm = new TableModel();
DefaultTableModel model = new DefaultTableModel();
model.setColumnIdentifiers(columnNames);
//DefaultTableModel model = new DefaultTableModel(tm.getData1(), tm.getColumnNames());
//table = new JTable(model);
table = new JTable();
table.setModel(model);
table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
table.setFillsViewportHeight(true);
JScrollPane scroll = new JScrollPane(table);
scroll.setHorizontalScrollBarPolicy(
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scroll.setVerticalScrollBarPolicy(
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
from = (String) c1.getSelectedItem();
//String textvalue = textbox.getText();
String uname = "";
String email = "";
String pass = "";
String cou = "";
try {
/* pst = con.prepareStatement("select * from emp where UNAME='" + from + "'");*/
pst = con.prepareStatement("select distinct Section.Section_Name,Report.Report_Name,Report.Link,Contact.Contact_Name "
+ "FROM (( Section INNER JOIN Report ON Report.Section_ID=Section.Section_ID ) INNER JOIN Contact ON Contact.Contact_ID=Report.Contact_ID ) LEFT JOIN Metrics ON Metrics.Report_ID=Report.Report_ID "
+ " WHERE Section.Section_Name LIKE '%"+from+"%' OR Report.Report_Name LIKE '%"+from+"%' OR Metrics.Metric_Name LIKE '%"+from+"%' OR Contact.Contact_Name LIKE '%"+from+"%' ");
ResultSet rs = pst.executeQuery();
int i = 0;
while (rs.next()) {
uname = rs.getString("Section_Name");
email = rs.getString("Report_Name");
pass = rs.getString("Contact_Name");
cou = rs.getString("Link");
model.addRow(new Object[]{uname, email, pass, cou});
i++;
}
if (i < 1) {
JOptionPane.showMessageDialog(null, "No Record Found", "Error", JOptionPane.ERROR_MESSAGE);
}
if (i == 1) {
System.out.println(i + " Record Found");
} else {
System.out.println(i + " Records Found");
}
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
}
frame1.add(scroll);
frame1.setVisible(true);
frame1.setSize(1000, 400);
}
public static void main(String args[]) {
new r_search();
}
}
The following worked for me using Eclipse and JavaSE-1.7. Eclipse shows the following in its Package Explorer
The [folders] and files in my project folder are
[C:]
[Users]
[Gord]
[workspace]
[com.example.jartest]
[src]
[com]
[example]
[jartest]
JarTestMain.java
[resources]
JarData.mdb
The Java code in JarTestMain.java is
package com.example.jartest;
import java.io.*;
import java.nio.file.*;
import java.sql.*;
public class JarTestMain {
public static void main(String[] args) {
String mdbFileName = "JarData.mdb";
String tempDbPath = System.getenv("TEMP").replace('\\', '/') + "/" + mdbFileName;
// retrieve .mdb database from the JAR file and save to %TEMP% folder
InputStream strmIn = JarTestMain.class.getResourceAsStream("resources/" + mdbFileName);
File f = new File(tempDbPath);
try {
Files.copy(strmIn, f.toPath(), StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
e.printStackTrace();
}
// open the copy of the database in %TEMP% folder and read from its table
String connectionString =
"jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};" +
"DBQ=" + tempDbPath;
try (Connection con = DriverManager.getConnection(connectionString)) {
Statement s = con.createStatement();
ResultSet rs = s.executeQuery("SELECT * FROM Table1");
while (rs.next()) {
System.out.println(String.format(
"%d: %s",
rs.getInt("ID"),
rs.getString("TextField")));
}
rs.close();
con.close();
f.delete();
} catch (Exception e) {
e.printStackTrace();
}
}
}
After I exported the project to a "Runnable JAR file" named JarTest.jar I was able to run it on my 32-bit Windows test machine using...
"C:\Program Files\Java\jre7\bin\java" -jar JarTest.jar
...and on my 64-bit Windows development machine via
"C:\Program Files (x86)\Java\jre7\bin\java" -jar JarTest.jar

how to retrieve data from db automatic of given id?

Hi i am using swing for data retrieving i i am able to retrieve data on action perform.
but i want to retrieve data when i run this program automatic given id data retrieve from
database.
Help me Please
Thanks
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.swing.*;
public class BankGui extends JApplet implements ActionListener{
// GUI components
JLabel lblUser, lblPass,lblnull,lbl1;
JTextField txtid;
JTextField txtUser;
JTextField txtPass;
JButton btnOk, btnClear;
// connections to MYSQL
private static Connection connection = null;
private static Statement statement = null;
private static ResultSet resultSet = null;
//public static Scanner in = new Scanner(System.in);
public void init(){
Container c = getContentPane();
c.setLayout( new FlowLayout() );
lblUser = new JLabel( "Username: " );
c.add( lblUser );
txtUser = new JTextField( 10 );
c.add( txtUser );
lblPass = new JLabel( "Password:" );
c.add( lblPass );
txtPass = new JTextField( 10 );
c.add( txtPass );
lbl1 = new JLabel( "Enter id" );
c.add( lbl1);
txtid=new JTextField(10);
c.add(txtid);
btnOk = new JButton( "OK" );
btnOk.addActionListener( this );
c.add( btnOk );
lblnull= new JLabel("");
c.add(lblnull);
}
#Override
public void actionPerformed(ActionEvent e) {
PreparedStatement stmt=null;
boolean isFound=false;
try{
connection = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/test", "root", "");
// String sql="SELECT uname FROM users1 WHERE uname=? and pwd=?";
String sql = "SELECT * FROM users WHERE uid = '"+2+"'";
stmt=connection.prepareStatement(sql);
//stmt.getString(1,txtUser.getText());
// stmt.setString(2,txtPass.getText());
resultSet=stmt.executeQuery();
if(resultSet.next()){
isFound=true;
// String s=resultSet.getString(1);
// String s1=resultSet.getString(2);
//System.out.println(s);
txtPass.setText(resultSet.getString(1));
lblnull.setText(resultSet.getString(2));
// System.out.println(s1);
}
//
}catch(SQLException ex){
System.err.println(ex);
}finally{
if(stmt!=null){
try{
stmt.close();
}catch(Exception ex) { /* */ }
}
if(connection!=null){
try{
connection.close();
}catch(Exception ex) { /* */ }
}
}
}
static {
try{
Class.forName("com.mysql.jdbc.Driver");
}catch(Exception ex) {
System.err.println(ex);
}
}
}
If datatype of uid is int then your query should be
String sql = "SELECT * FROM users WHERE uid = "+2;
'2' is used for varchar datatype
In addition to #AJ answer I have some tips:
Database calls are time consuming tasks and may block the Event Dispatch Thread (a.k.a. EDT) causing the GUI become unresponsive. To avoid this issue consider use a SwingWorker to perform database calls in a background thread and update Swing components in the EDT. See more in Concurrency in Swing trail.
It's not a good practice ignore exceptions in a catch block: catch(Exception ex){}
Note your query is vulnerable to SQL injection attaks. To avoid this you may want to try PreparedStatement instead.
Example:
String sql = "SELECT * FROM users WHERE uid = ?";
PreparedStatement pst = connection.prepareStatement(sql);
pst.setInt(1, 2); // see PreparedStatement.setInt(index, value)
ResultSet rs = pst.executeQuery();

DB creation and deletion in mysql

I use the following code to create new Database. If the given Database name is same as existing Database name means the existing Database need to be deleted else the new data base need to be created with the given name. I have error in creating new database.
package db1;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import java.sql.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class Main implements ActionListener
{
JTextField txt;
JButton create;
JFrame frame;
JPanel panel;
JOptionPane jop;
//Font font = UIManager.getFont("txt.font");
public Main()
{
frame=new JFrame();
panel=new JPanel();
txt=new JTextField(10);
create=new JButton("create");
create.setBounds(20, 200, 50, 40);
panel.add(txt);
panel.add(create);
create.addActionListener(this);
frame.add(panel);
// n.getContentPane().add(new textf());
frame.setSize(440,310);
frame.setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
Connection con = null;
try{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/vijay1","root","root");
try{
Statement st = con.createStatement();
String database=txt.getText();
st.executeUpdate("DROP DATABASE IF EXISTS "+database);
JOptionPane.showMessageDialog(frame,"EXISTING DATABASE DELETED");
st.executeUpdate("CREATE DATABASE "+database);
JOptionPane.showMessageDialog(frame,"DATABASE CREATED");
}
catch (SQLException s){
System.out.println("SQL statement is not executed!");
}
}
catch (Exception ea){
ea.printStackTrace();
}
}
public static void main(String[] args)
{
new Main();
}
}
Try this as your inner try block, hope this will help.
try
{
String database=txt.getText();
String query = "if exists(select * from sys.databases where (name = ?))"
+ "drop database " + database
+ "create database " + database;
PreparedStatement statement = con.prepareStatement(query);
statement.setString(1, database);
statement.executeUpdate();
JOptionPane.showMessageDialog(frame,"EXISTING DATABASE DELETED");
JOptionPane.showMessageDialog(frame,"DATABASE CREATED");
}
Regards

Categories