Getting Connection to mysql database using Java? - java

I am having problem in connecting to mysql database when I am using this code.I have already checked that port number is 3128.So there is no issue about that.I checked it and I think problem is in
connection= DriverManager.getConnection("jdbc:mysql://localhost:3128/gcc","root", "root");
There is no error when compiling.Can someone help me with this?
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
import java.sql.*;
//import java.net.*;
public class Main extends Applet implements ActionListener
{
TextArea tarea;
Button bsubmit;
public void init()
{
setBackground(new Color(0,0,0));
setForeground(Color.white);
Label l1=new Label("Write your code : ");
l1.setFont(new Font("lucida console",Font.PLAIN,25));
l1.setSize(200,30);
tarea=new TextArea();
tarea.setFont(new Font("lucida console",Font.PLAIN,18));
tarea.setForeground(new Color(0,0,0));
tarea.setSize(600,250);
bsubmit=new Button("Submit");
bsubmit.setFont(new Font("lucida console",Font.PLAIN,15));
bsubmit.setBackground(new Color(255,255,255));
bsubmit.setForeground(new Color(0,0,0));
bsubmit.setSize(100,30);
add(l1);
add(tarea);
add(bsubmit);
setLayout(null);
l1.setLocation(40,40);
tarea.setLocation(40,100);
bsubmit.setLocation(40,400);
bsubmit.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
if(ae.getSource()==bsubmit)
{
Connection connection=null;
try
{
Class.forName("com.mysql.jdbc.Driver");
connection= DriverManager.getConnection("jdbc:mysql://localhost:3128/gcc","root", "root");
Statement stmt = connection.createStatement();
stmt.executeUpdate("CREATE TABLE test2 (code VARCHAR(254))");
}
catch (Exception e) {}
}
}
}

Java database drivers are the worst thing. I remember, I had my first JDBC driver (or let's say: a working transaction;) to be installed within "only" 2 days, and I know a guy who had two weeks, lol.
In most of the time the very last issue is a SQL problem. Because you need to give the rights to the user as "username"#"IP". You find the user information in the database information_schema in the table user_privileges. There exist enough tutorials how to handle them, but I like 'username'#'%' to get all privileges in a test environment. smile
This may help you: http://dev.mysql.com/doc/refman/5.1/de/adding-users.html
Yeah, those damn SQL rights... ;D
#Luiggi: That's certainly no silly question! I had hours to find that out!! I mean, which beginner knows that the Java sql classes are only xxxxxxx interfaces with no implemented code?! %D
EDIT
And anyway:
Class.forName("...driverblabla...");
Does this code line look like Java? Nooo, its a xxxxxx compiler hack or whatever! But it works, it really DOES something!!
Oh, but for certain driver implementations this won't work, you need this:
Class.forName("...driverblabla...").newInstance();
LMAO!
#Abhinav: Add this line above your getConnection-line:
Class.forName("com.mysql.jdbc.driver").newInstance();
And don't think one second about what it exactly does (I know it, but...let's screw it ;)

Related

Issues with retrieving data from Access database using criteria from JTextField objects

I have created user login window in java and i am getting some issues regarding retrieving saved data from ms access database.
Here is my code:
package databaseretrievedata;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.*;
import javax.swing.*;
public class Databaseretrievedata {
Databaseretrievedata(){
JFrame edit=new JFrame();
edit.setBounds(300,200,550,120);
edit.setUndecorated(false);
edit.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel p=new JPanel();
p.setBounds(0,0,600,400);
edit.add(p);
JTextField field=new JTextField(20);
field.setBounds(100,200,120,20);
p.add(field);
JTextField field1=new JTextField(20);
field1.setBounds(100,300,120,20);
p.add(field1);
JButton b=new JButton("Click Me");
b.setBounds(0,100,100,20);
p.add(b);
JRootPane pane=b.getRootPane();
pane.setDefaultButton(b);
b.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
try {
Connection conn=DriverManager.getConnection("jdbc:ucanaccess://C:\\Users\\MUHAMMAD SHAHAB\\real estate.accdb");
Statement st=conn.createStatement();
String sql="select Username,Password from table where Username='"+field+"'and Password='"+field1+"'";
ResultSet rs=st.executeQuery(sql);
if(rs.next())
{
JFrame editframe=new JFrame();
editframe.setBounds(300,200,400,200);
editframe.setUndecorated(false);
editframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
editframe.setVisible(true);
}
else
{
JOptionPane.showMessageDialog(null,"No record Found");
}
}
catch (Exception ex)
{
JOptionPane.showMessageDialog(null, ex);
}
}
});
edit.setVisible(true);
}
public static void main(String[] args) {
Databaseretrievedata v=new Databaseretrievedata();
}
}
Here is the file in the database where i saved my data.[![enter image description here][1]][1]
I have created one text field for username and password field for getting password from the user inside JFrame and when i entered the same username and password which i saved in ms access database i got 'No record Found'although i have saved that data in the database and i want this,that when user enter username and password in the provided fields then a new JFrame opens up.
I am not pretty sure where i am doing mistake.
#Swager you are missing getText() method from your query
you should write your sql like this String sql = "select Username,Password from simba where Username='"+field.getText()+"'and Password='"+field1.getText()+"'";
Your sql is missing something, your statement:
String sql="select Username,Password from simba where Username='"+field+"'and Password='"+field1+"'";
This won't be what you're actually expecting here. Since the JTextField does not provide a special toString() method for its text, so that's why you can't find any matching entry in your database.
You need to retrieve the entered username, respectively the password by calling the getText() method on the JTextField:
String sql = "select Username,Password from simba where Username='"+field.getText()+"'and Password='"+field1.getText()+"'";
In such cases it is helpful to also print your query to the console to spot mistakes instantly

JDBC - csv file Error

I have a simple question, somehow I can't see where my problem is.
I've got a csv file in my C:/Temp folder. I would like to connect to the csv to get some data (depending on specific row data, different rows,...).
So I downloaded the csvjdbc-1.0-28.jar file and added it to the build path.
I wrote the code as shown below but always get the error:
"java.sql.SQLException: No suitable driver found for"
I have seen some people got also problems with it but I did not get the problem behind the issue I have. I know it has something to do with the Connection conn. Do I need to do some additional JDBC settings or how can I add the path for the connection?
Thanks in advance!
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.relique.jdbc.csv.CsvDriver;
public class Main_Class {
public static void main(String[] args) {
try {
try {
Class.forName("org.relique.jdbc.csv.CsvDriver");
Connection conn = DriverManager
.getConnection("c:\\temp\\Spieltage_log.txt");
Statement stmt = conn.createStatement();
ResultSet results = stmt
.executeQuery("select * from Offensiver_Zweikampf");
boolean append = true;
CsvDriver.writeToCsv(results, System.out, append);
conn.close();
System.out.println(results);
} catch (SQLException e) {
e.printStackTrace();
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
// JFrame fenster = new Main_Menue();
}
}
According to the example at (http://csvjdbc.sourceforge.net/)-
// Create a connection. The first command line parameter is
// the directory containing the .csv files.
// A single connection is thread-safe for use by several threads.
Connection conn = DriverManager.getConnection("jdbc:relique:csv:" + directoryName);
In your case it should be -
Properties props = new Properties();
props.put("fileExtension", ".txt");
Connection conn = DriverManager.getConnection("jdbc:relique:csv:C:\\temp", props);
Also you've put the content in a txt file, so you'll need to specify a custom property with the fileExtension as '.txt' in it.
Your resultSet object than can query the file using the below syntax -
ResultSet results = stmt.executeQuery("select * from Spieltage_log");
The URL string passed to DriverManager.getConnection() needs to specify the driver name:
Connection conn = DriverManager
.getConnection("jdbc:relique:csv:c:\\temp");
Besides, you need to pass the directory of the csv file and not the file itself. See answer of Sachin who in the meantime posted detailed instructions.
Sorry my fault: I saved the file as a xlsx file and not csv file. So solved it now and it worked! Thanks a lot guys! Appreciate your help

How do I add multiple items from a jcombobox from a database in ms access

import java.sql.*;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
class ComboExample {
Connection con;
Statement st;
ResultSet rs;
ComboExample() {
JFrame f = new JFrame();
f.getContentPane().setLayout(null);
final JComboBox combo = new JComboBox();
try {
String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
Class.forName(driver);
String db = "jdbc:odbc:TTracking";
con = DriverManager.getConnection(db);
// Getting database info
DatabaseMetaData meta = con.getMetaData();
System.out.println("Server name: " +
meta.getDatabaseProductName());
System.out.println("Server version: " +
meta.getDatabaseProductVersion());
System.out.println("");
System.out.println("Creating statement...");
st = con.createStatement();
String sql = "SELECT Trailer FROM TrailerLocationMaster";
ResultSet rs = st.executeQuery(sql);
while (rs.next()) {
String trailer = rs.getString("Trailer");
combo.addItem(trailer);
System.out.println(rs.getString("Trailer"));
combo.setVisible(true);
}
}
catch (Exception ex) {
}
combo.setBounds(20, 50, 150, 20);
f.add(combo);
f.setSize(400, 200);
f.setVisible(true);
}
public static void main(String[] args) {
ComboExample c = new ComboExample();
}
}
The combo-box displays correctly, but only one item from the database table appears why is that? and how do I allow multiple items to be in jcombobox from database? Also why does it always complain with and advises suppress warnings?
Don't use a null layout and setBounds(...). Swing was designed to be used with layout managers.
There is no need for comboBox.setVisible(true) since Swing components (except for top level containers) are visible by default.
Also why does it always complain with and advises suppress warnings?
You haven't specified the type of data that will adding the to the model of the combo box. You are adding String data so you should be using:
JComboBox<String> combo = new JComboBox<String>();
Read up on Generics for more information.
how do I allow multiple items to be in jcombobox from database?
You don't do anything special. Your code looks reasonable since you have a while loop and you invoked the addItem(...) method.
If you only have one item, then I would guess your query only returns a single item. Your output should verify this. Add more data to your table.

Database locked while trying to open multiple jframes

My problem is , while opening a jframe which is including different informations than my main jframe , when i tried to work on this jframe, for example inserting data to SQLite manager's database . But it's giving me Database locked error.I can insert data from my main jframe which i'm opening new jframes with jcombobox. I hink i know source but i dont know how to fix this. I think i need to close my main jframe which i open other frames. So sqlite database can storage this frames datas. Here i'll give to you how can i open jframes with jcombobox and how i'm trying to insert a data to database. Please help me or , leave a comment what're you thinking about this problem. Am i wrong with source idea or true. I need your helps guys. Thanks for reading.
1: This codes how i'm opening jframes with combobox.
public void comboselect(){
int d =ComboBox_name.getSelectedIndex();
if (d==0){
CezalıUye s=new CezalıUye();
s.setVisible(true);
dispose();
}
if(d==1){
DeaktifUye z=new DeaktifUye();
z.setVisible(true);
dispose();
}
if(d==2){
TatbikatForm l=new TatbikatForm();
l.setVisible(true);
dispose();
}
}
2:This codes how i'm trying to insert data which i opened from jcombobox.
private void cmd_saveActionPerformed(java.awt.event.ActionEvent evt) {
try{
String sql = "Insert into cezalitablosu (KimTarafından,Kime,Neden,Kaçıncı,Tarih) values (?,?,?,?,?)";
pst=conn.prepareStatement(sql);
pst.setString(1, jTextField1.getText());
pst.setString(2, jTextField2.getText());
pst.setString(3, jTextField3.getText());
pst.setString(4, jTextField4.getText());
pst.setString(5, jTextField5.getText());
pst.execute();
JOptionPane.showMessageDialog(null, "Kaydedildi!");
}
catch(Exception e)
{
e.printStackTrace();
JOptionPane.showMessageDialog(null, e);
}
Update_table();
}
execute() can not be use for insert,update and delete.
For insert,update and delete always use
executeUpdate();

Retrieving text from JTextField

The concept of my code is that, it will initially retrieve distinct names from a column 'tname' of my access database table 'try'. It will add those items in a combobox. Once we select an item in the combo box, the data of the row containing tname as the selected item is retrieved and showed in textfields. Then I will make some changes to the text field content. After that, if I click 'Save' button, then all the data of the row containing tname as the selected combobox item must be updated with the new content in the textfields.
Everything goes fine, except the last one. When I click 'save' it considers only the previous text(the one intially retrieved from the database when we select combobox) and not the changes made to it. Kindly help me to diagnose the problem.
Thanks in advance.
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.table.*;
import java.util.Date;
import java.sql.*;
import java.text.*;
public class gut implements ActionListener
{
JComboBox ctn;
JTextField cm,exd,stk,cst,sup,snum,r;
String stn,scm,sexd,sst,scst,ssup,ssnum,sr,icm,iexd,istk,icst,isup,isnum,ir;
JLabel lt,lc,le,ls,lcs,lsp,lspn,lr;
JButton s;
JFrame gp=new JFrame();
public gut()
{
gp.setSize(500,500);
gp.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gp.setLayout(null);
lt=new JLabel("Tablet Name",JLabel.RIGHT);
lc=new JLabel("Composition",JLabel.RIGHT);
le=new JLabel("Expiry Date (dd/mm/yyyy)",JLabel.RIGHT);
ls=new JLabel("Stock",JLabel.RIGHT);
lcs=new JLabel("Cost",JLabel.RIGHT);
lsp=new JLabel("Supplier",JLabel.RIGHT);
lspn=new JLabel("Supplier Number",JLabel.RIGHT);
lr=new JLabel("Rack",JLabel.RIGHT);
lt.setBounds(100,120,120,20);
lc.setBounds(100,140,120,20);
le.setBounds(60,160,160,20);
ls.setBounds(100,180,120,20);
lcs.setBounds(100,200,120,20);
lsp.setBounds(100,220,120,20);
lspn.setBounds(100,240,120,20);
lr.setBounds(100,260,120,20);
ctn=new JComboBox();
cm=new JTextField();
exd=new JTextField();
stk=new JTextField();
cst=new JTextField();
sup=new JTextField();
snum=new JTextField();
r=new JTextField();
ctn.setBounds(240,120,120,20);
cm.setBounds(240,140,120,20);
exd.setBounds(240,160,120,20);
stk.setBounds(240,180,120,20);
cst.setBounds(240,200,120,20);
sup.setBounds(240,220,120,20);
snum.setBounds(240,240,120,20);
r.setBounds(240,260,120,20);
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection conn=DriverManager.getConnection("jdbc:odbc:vasantham","","");
Statement st=conn.createStatement();
ResultSet rs=st.executeQuery("select DISTINCT tname from try");
while(rs.next())
{
ctn.addItem(rs.getString("tname"));
}
conn.close();
}
catch(Exception e)
{
}
gp.add(lt);gp.add(ctn);
gp.add(lc);gp.add(cm);
gp.add(le);gp.add(exd);
gp.add(ls);gp.add(stk);
gp.add(lcs);gp.add(cst);
gp.add(lsp);gp.add(sup);
gp.add(lspn);gp.add(snum);
gp.add(lr);gp.add(r);
ctn.addActionListener(this);
s=new JButton("Save");
s.setBounds(200,300,100,20);
gp.add(s);
s.addActionListener(this);
gp.setVisible(true);
}
public void actionPerformed(ActionEvent evt)
{
String act=evt.getActionCommand();
String scb=(String)ctn.getSelectedItem();
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection conn=DriverManager.getConnection("jdbc:odbc:vasantham","","");
Statement st=conn.createStatement();
ResultSet rs=st.executeQuery("select * from try where tname='"+scb+"'");
SimpleDateFormat formatter=new SimpleDateFormat("dd/MM/yyyy");
while(rs.next())
{
icm=rs.getString("composition");
iexd=formatter.format(rs.getDate("exdate"));
istk=Integer.toString(rs.getInt("stock"));
icst=rs.getString("cost");
isup=rs.getString("sup");
isnum=rs.getString("supnum");
ir=rs.getString("rack");
}
cm.setText(icm);
exd.setText(iexd);
stk.setText(istk);
cst.setText(icst);
sup.setText(isup);
snum.setText(isnum);
r.setText(ir);
conn.close();
}
catch(Exception e)
{
System.out.println(e);
}
if(act.equals("Save"))
{
scm=cm.getText();
sexd=exd.getText();
sst=stk.getText();
scst=cst.getText();
ssup=sup.getText();
ssnum=snum.getText();
sr=r.getText();
System.out.println(scm+","+sexd+","+sst+","+scst+","+ssup+","+ssnum+","+sr);
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection conn=DriverManager.getConnection("jdbc:odbc:vasantham","","");
PreparedStatement ps=conn.prepareStatement("UPDATE try set composition=?,exdate=?,stock=?,cost=?,sup=?,supnum=?,rack=? where
tname=?");
ps.setString(1,scm);
ps.setString(2,sexd);
ps.setString(3,sst);
ps.setString(4,scst);
ps.setString(5,ssup);
ps.setString(6,ssnum);
ps.setString(7,sr);
ps.setString(8,scb);
ps.executeUpdate();
JOptionPane.showMessageDialog(null,"Your entry has been stored successfully!!!");
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null,"Error!Try again!");
System.out.println(e);
}
}
}
public static void main(String[] args)
{
new gut();
}
}
On top of what everybody else has already said, if you REALLY want to use a single action listener, you are going to need to work out which action has actually occurred.
You could check the source of the ActionEvent (evt.getSource()) or, more appropriately, you could assign a action command to each component using the action listener.
Check out JComboBox.setActionCommand(...) and JButton.setActionCommand(...)
After that, it's a simple case of checking the ActionEvent.getActionCommand() property to determine the correct action to take.
The problem is that every time you hit the "Save" button you are retrieving the information from the database over again, so, you overwrite the TextFields and then you read from the TexFields content. Try to take out this part:
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection conn = DriverManager.getConnection
("jdbc:odbc:vasantham", "", "");
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery("select * from try where tname='"
+ scb + "'");
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
while (rs.next()) {
icm = rs.getString("composition");
iexd = formatter.format(rs.getDate("exdate"));
istk = Integer.toString(rs.getInt("stock"));
icst = rs.getString("cost");
isup = rs.getString("sup");
isnum = rs.getString("supnum");
ir = rs.getString("rack");
}
cm.setText(icm);
exd.setText(iexd);
stk.setText(istk);
cst.setText(icst);
sup.setText(isup);
snum.setText(isnum);
r.setText(ir);
conn.close();
} catch (Exception e) {
System.out.println(e);
}
from the action performed method.
Every time your action event is fired, you read data from DB and write it into the textfields.
You can change that text and it will be displayed correctly in your textfields. But when you click save, all your changes are overwritten with the DB values again.
So you have to separate the functionalities "read from DB" and "write changes".
edit:
oops, too slow..
Your actionPerformed() function retrieves the information from the database every time. If you press the Save button it will first retrieve the information and then save the information if the action command is "Save". This is why you always get the information that's currently in the database from getText() when pressing the Save button.
Make a different function / actionListener to execute when the Save button is pressed or take the part of the code that updates the text fields else where.
Try something like this instead:
JButton saveButton = new JButton( new AbstractAction("save") {
#Override
public void actionPerformed( ActionEvent e ) {
// Save the info here or just call a function that will.
}
});

Categories