What I am trying to do is to add data on mysql database using my applet page. my idea is to fill up the textfields then when i hit the save button all the text's will add to mySQL database. But i'm having an error saying
Access Denied: java.security.AccessControlException:access denied
(java.io.FilePermision "\C:\Program Files(x86)\MySQL\mysql-connector-java-5.1.30\mysql-connector-java-5.1.30-bin.jar" "read")
thank you in advance. here's my code: :((
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.SwingUtilities;
import javax.swing.JApplet;
import java.sql.*;
import java.net.*;
public class AddBook extends JApplet
{
JButton btnSave, btnCancel;
JLabel lblIsbn, lblTitle, lblCategory, lblAuthor, lblYPublish, lblPublisher, lblCopies, lblYear, lblMsg1;
JTextField txtTitle, txtCategory;
JTextField txtIsbn, txtAuthor, txtPublisher, txtCopies, txtYear;
String ttitle, tauthor, tpublisher, tcategory, tisbn, tyear, tqty;
public void init()
{
Font fonttxt = new Font("Calibri", Font.PLAIN, 16);
Font fontlbl = new Font("Calibri",Font.BOLD, 14);
Font fontbtn = new Font("Calibri",Font.BOLD, 16);
Font fontTitle = new Font("Arial ",Font.BOLD,30);
setLayout(null);
setSize(410, 400);
setBackground(Color.gray);
btnSave = new JButton("Save");
btnSave.setFont(fontbtn);
btnCancel = new JButton("Cancel");
btnCancel.setFont(fontbtn);
lblMsg1 = new JLabel ("ADD BOOK");
lblMsg1.setFont(fontbtn);
lblIsbn = new JLabel("ISBN :");
lblIsbn.setFont(fontlbl);
lblTitle = new JLabel ("Title :");
lblTitle.setFont(fontlbl);
lblCategory = new JLabel ("Category :");
lblCategory.setFont(fontlbl);
lblAuthor = new JLabel ("Author :");
lblAuthor.setFont(fontlbl);
lblYear = new JLabel ("Year Published :");
lblYear.setFont(fontlbl);
lblPublisher = new JLabel ("Publisher :");
lblPublisher.setFont(fontlbl);
lblCopies = new JLabel ("Number of Copies :");
lblCopies.setFont(fontlbl);
JTextField txtIsbn = new JTextField ("",100);
txtIsbn.setFont(fonttxt);
JTextField txtTitle = new JTextField ("",100);
txtTitle.setFont(fonttxt);
JTextField txtCategory = new JTextField ("",100);
txtCategory.setFont(fonttxt);
JTextField txtAuthor = new JTextField ("",100);
txtAuthor.setFont(fonttxt);
JTextField txtPublisher = new JTextField ("",100);
txtPublisher.setFont(fonttxt);
JTextField txtCopies = new JTextField ("",100);
txtCopies.setFont(fonttxt);
JTextField txtYear = new JTextField ("",100);
txtYear.setFont(fonttxt);
lblMsg1.setBounds(10,10,200,40);
lblIsbn.setBounds(10,50,250,30);
txtIsbn.setBounds(130,50,250,30);
lblTitle.setBounds(10,90,250,30);
txtTitle.setBounds(130,90,250,30);
lblCategory.setBounds(10,130,250,30);
txtCategory.setBounds(130,130,250,30);
lblAuthor.setBounds(10,165,250,30);
txtAuthor.setBounds(130,165,250,30);
lblPublisher.setBounds(10,200,250,30);
txtPublisher.setBounds(130,200,250,30);
lblCopies.setBounds(10,240,250,30);
txtCopies.setBounds(130,240,250,30);
lblYear.setBounds(10,280,250,30);
txtYear.setBounds(130,280,250,30);
btnSave.setBounds(40,320,150,35);
btnCancel.setBounds(200,320,150,35);
add(lblMsg1);
add(txtIsbn);
add(txtTitle);
add(txtCategory);
add(txtAuthor);
add(txtPublisher);
add(txtCopies);
add(txtYear);
add(lblIsbn);
add(lblTitle);
add(lblCategory);
add(lblAuthor);
add(lblPublisher);
add(lblCopies);
add(lblYear);
add(btnSave);
add(btnCancel);
tisbn = txtIsbn.getText();
tyear = txtYear.getText();
tqty = txtCopies.getText();
ttitle = txtTitle.getText();
tauthor = txtAuthor.getText();
tcategory = txtCategory.getText();
tpublisher = txtPublisher.getText();
btnSave.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
//Connection con = null;
//Statement st = null; 1
PreparedStatement pstmt;
Connection con;
if(ae.getSource() == btnSave)
{
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost/library_system", "root", "password");
con.setAutoCommit(false);
pstmt = con.prepareStatement ("INSERT INTO book_records VALUES (?, ?, ?, ?, ?, ?, ?)");
pstmt.setString(1, tisbn);
pstmt.setString(2, ttitle);
pstmt.setString(3, tauthor);
pstmt.setString (4, tyear);
pstmt.setString(5, tpublisher);
pstmt.setString(6, tcategory);
pstmt.setString(7, tqty);
pstmt.executeUpdate();
con.commit();
pstmt.close();
}
catch(Exception err)
{
JOptionPane.showMessageDialog(null, "Access Denied: "+err );
}
}
}
}
});
}
}
Could you please try the mysql connection as
Class.forName("com.mysql.jdbc.Driver");
Connection conn = null;
conn = DriverManager.getConnection("jdbc:mysql://hostname:port/dbname","username", "password");
I think you are missing port.
The error says simply "Access denied" problem from your Java program to the directory where MySQL jar exists.
You shouldn't link (reference) jar file in another directory from Java application.
The problem can be simply solved by adding the required mysql-connector-java-5.1.30-bin.jar to your application's class path.
Related
I want to add another column in mysql either by using java or manually in the mysql application. This is my java code and I need to add a column named book_id
package liblog;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
public class AStudents extends JFrame {
private JTextField admissionnumber;
private JTextField firstname;
private JTextField lastname;
private JTextField surname;
private JTextField house;
private JTextField dome;
private JButton add;
private JButton back;
private static Connection conn;
JFrame frame = new JFrame();
ImageIcon icon = new ImageIcon("C:/Users/User/workspace/Login/src/liblog/parklands.png");
JPanel panel = new JPanel(new GridBagLayout());
JPanel panel2 = new JPanel();
JPanel panel3 = new JPanel();
JLabel admissionNumber = new JLabel();
JLabel firstName = new JLabel();
JLabel lastName = new JLabel();
JLabel surName = new JLabel();
JLabel mainHouse = new JLabel();
JLabel mainDome = new JLabel();
AStudents(){
super("DR.RIBEIRO PARKLANDS SCHOOL");
setLayout(new FlowLayout(FlowLayout.LEFT,3,100));
setBounds(500,500,550,550);
setLocation(500,200);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
Container con = this.getContentPane();
con.setBackground(Color.GRAY);
con.add(panel);
panel.setLayout(new BoxLayout(panel,BoxLayout.Y_AXIS));
panel2.setLayout(new FlowLayout(FlowLayout.CENTER,3,10));/*X axis,Y axis*/
panel3.setLayout(new BoxLayout(panel,BoxLayout.LINE_AXIS));
panel.setBackground(Color.GRAY);
/* admissionNumber=new JLabel("Admission Number");
admissionNumber.setAlignmentX(0.0f);
admissionnumber = new JTextField("No",30);
admissionnumber.setAlignmentX(0.0f);*/
firstName=new JLabel("First Name");
firstName.setAlignmentX(0.0f);
firstname = new JTextField("Name",20);
firstname.setAlignmentX(0.0f);
lastName=new JLabel("Last Name");
lastName.setAlignmentX(0.0f);
lastname = new JTextField("Name",20);
lastname.setAlignmentX(0.0f);
surName=new JLabel("Surname");
surName.setAlignmentX(0.0f);
surname = new JTextField("Name",20);
surname.setAlignmentX(0.0f);
mainHouse=new JLabel("House");
mainHouse.setAlignmentX(0.0f);
house = new JTextField("House",20);
house.setAlignmentX(0.0f);
mainDome=new JLabel("Dome");
mainDome.setAlignmentX(0.0f);
dome = new JTextField("Dome",20);
dome.setAlignmentX(0.0f);
add = new JButton("Add Student");
back = new JButton("Back");
add.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Insert into SQL:
try {
PreparedStatement insert = conn.prepareStatement("INSERT INTO students (first_name, last_name, surname, house, dome) VALUES (?,?,?,?,?)");
insert.setString(1, firstname.getText());
insert.setString(2, lastname.getText());
insert.setString(3, surname.getText());
insert.setString(4, house.getText());
insert.setString(5, dome.getText());
insert.execute();
ABooks abooks = new ABooks();
dispose();
}
catch(Exception ex) {
System.out.println(ex);
}
}
});
back.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Admin admin = new Admin();
dispose();
}
});
//panel.add(admissionNumber);
//panel.add(admissionnumber);
panel.add(firstName);
panel.add(firstname);
panel.add(lastName);
panel.add(lastname);
panel.add(surName);
panel.add(surname);
panel.add(mainHouse);
panel.add(house);
panel.add(mainDome);
panel.add(dome);
panel.add(add);
panel.add(back);
try {
conn = getConnection();
createTable();
}
catch(Exception ex) {
System.out.println(ex);
}
setVisible(true);
}
/*public static void main(String[]args) throws Exception{new AStudents();
createTable();
}*/
//Table
public static void createTable() throws Exception{
try{
Connection conn = getConnection();
PreparedStatement create = conn.prepareStatement("CREATE TABLE IF NOT EXISTS students(id int NOT NULL AUTO_INCREMENT,first_name varchar(45),last_name varchar(45),surname varchar(320),house varchar(50),dome varchar(50),book_id varchar(50),PRIMARY KEY(id))");
create.executeUpdate();
}catch(Exception e){System.out.println(e);}
finally {
System.out.println("System Updated");};
}
//EndofTable
//DB
public static Connection getConnection() throws Exception{
try{
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/students?useSSL=false";
String username = "root";
String password = "toor";
Class.forName(driver);
Connection conn = DriverManager.getConnection(url,username,password);
System.out.println("Connected");
return conn;
}catch(Exception e){
System.out.println(e);
}
return null;
}
//DB
}
The application is giving me the following error which I cannot get rid of
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'borrow_id' in 'field list'
This is the other code http://www.rapidtables.com/tools/notepad.htm
In your SQL DB:
ALTER TABLE students ADD book_id varchar(50)
I'm guessing as to the datatype of the book_id.
Do you mean book_id or borrow_id? I don't see borrow_id in your code which is somewhat confusing and probably why you're getting down voted.
I have been given a college assignment to insert data into a mysql table using java applets. When I press the submit button, the command prompt throws a lot of exceptions(pic attached) and no data is inserted into the table.
Following is my code:
//Student registration Form (using applets and awt controls)
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import java.sql.*;
import java.util.*;
public class mysql4 extends Applet implements ActionListener{
Label l1 = new Label("Roll No. : ");
TextField t1 = new TextField("",10);
Label l2 = new Label("Name : ");
TextField t2 = new TextField("",20);
Label l3 = new Label("Gender : ");
CheckboxGroup radioGroup = new CheckboxGroup();
Checkbox r1 = new Checkbox("Male", radioGroup, false);
Checkbox r2 = new Checkbox("Female", radioGroup, true);
Label l4 = new Label("Hobbies : ");
Checkbox c1 = new Checkbox("Sports");
Checkbox c2 = new Checkbox("Cooking/Gardening");
Checkbox c3 = new Checkbox("Music");
Checkbox c4 = new Checkbox("Arts/Crafts");
Label l5 = new Label("Course Opted : ");
Choice l=new Choice();
Label l6 = new Label("FeedBack : ",Label.CENTER);
TextArea ta = new TextArea("",15,20);
Button b1 = new Button("Submit");
Button b2 = new Button("Reset");
public void init() {
l1.setAlignment(Label.CENTER);
add(l1);
add(t1);
add(l2);
add(t2);
add(l3);
add(r1);
add(r2);
add(l4);
add(c1);
add(c2);
add(c3);
add(c4);
add(l5);
l.add("BCA");
l.add("MCA");
l.add("PGDCA");
add(l);
add(l6);
add(ta);
b1.addActionListener(this);
add(b1);
b2.addActionListener(this);
add(b2);
}
public void actionPerformed(ActionEvent e){
if(e.getSource()==b1){
try{
String myDriver = "com.mysql.jdbc.Driver";
String myUrl = "jdbc:mysql://localhost:3306/sonoo?useSSL=false";
Class.forName(myDriver);
Connection con = DriverManager.getConnection(myUrl, "root", "12345678");
String query = "insert into details (RollNo, Name, Gender, Hobbies, Course, FeedBack)" + " values (?, ?, ?, ?, ?, ?)";
PreparedStatement ps = con.prepareStatement(query);
ps.setString (1, l1.getText());
ps.setString (2, l2.getText());
Checkbox chkr = radioGroup.getSelectedCheckbox();
ps.setString (3, chkr.getLabel());
Checkbox chk = radioGroup.getSelectedCheckbox();
ps.setString (4, chk.getLabel());
ps.setString (5, l.getSelectedItem());
ps.setString (6, ta.getText());
ps.execute();
con.close();
}catch(Exception ex){
ex.printStackTrace();
System.out.println(ex.getMessage());
}
}else if(e.getSource()==b2){
t1.setText(" ");
t2.setText(" ");
r1.setState(false);
r2.setState(true);
c1.setState(false);
c2.setState(false);
c3.setState(false);
c4.setState(false);
l.select("BCA");
ta.setText(" ");
}else{}
}
}
Output:
AppletLayout:
You're getting an AccessControlException when the driver is trying to read the file.encoding property. The applet needs to be given this permission for the driver to work.
I am new to java and I am trying to build a simple project that connects
to database then display it on JTable with MouseClick event. When i click in the row to transfer its content to JTextFields but it returns NullPointerException in line 225. Here's the full code of my project:
package Dbase;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
import java.sql.*;
import java.util.*;
#SuppressWarnings("serial")
public class MainForm extends JFrame {
Connection con;
Statement stmt;
ResultSet rs;
PreparedStatement pstmt;
#SuppressWarnings("rawtypes")
Vector columnNames = new Vector();
#SuppressWarnings("rawtypes")
Vector data = new Vector();
//JTable table;
private JPanel gui;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MainForm frame = new MainForm();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public MainForm() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
setLookAndFeel();
setSize(800,500);
gui = new JPanel();
gui.setLayout(new BorderLayout(5, 5));
setContentPane(gui);
DBConnect();
initComponents();
tbData();
}
public void DBConnect(){
try{
String host = "jdbc:mysql://localhost:3306/birthdb";
String uName = "admin";
String uPass = "46m1n";
// connection to mysql database
con = DriverManager.getConnection(host, uName, uPass);
stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
String sql = "SELECT * FROM childinfo";
rs = stmt.executeQuery(sql);
}
catch(SQLException er){
JOptionPane.showMessageDialog(MainForm.this, er.getMessage());
}
}
private void initComponents(){
//child's information
JLabel lblfirstName = new JLabel("FirstName", JLabel.RIGHT);
JLabel lbllastName = new JLabel("LastName", JLabel.RIGHT);
JLabel lblmiddleName = new JLabel("MiddleName", JLabel.RIGHT);
JLabel lblbirthDate = new JLabel("BirthDate",JLabel.RIGHT);
JLabel lblgender = new JLabel("Gender",JLabel.RIGHT);
JLabel lblbirthType = new JLabel("BirthType", JLabel.RIGHT);
JLabel lblmultiBirth = new JLabel("If Multiple Birth, Child Was", JLabel.RIGHT);
JLabel lblbirthOrder = new JLabel("BirthOrder", JLabel.RIGHT);
JLabel lblbirthWeight = new JLabel("BirthWeight",JLabel.RIGHT);
JLabel lblregistry = new JLabel("Registry",JLabel.RIGHT);
JTextField txtfirstName = new JTextField();
JTextField txtlastName = new JTextField();
JTextField txtmiddleName = new JTextField();
JTextField txtbirthDate = new JTextField();
JTextField txtgender = new JTextField();
JTextField txtbirthType = new JTextField();
JTextField txtmultiBirth = new JTextField();
JTextField txtbirthOrder = new JTextField();
JTextField txtbirthWeight = new JTextField();
JTextField txtregistry = new JTextField();
JButton newData = new JButton("New");
JButton updateData = new JButton("Update");
JButton deleteData = new JButton("Delete");
JButton printData = new JButton("Print");
JMenuBar menuBar;
JMenu menu;
JMenuItem menuItem;
menuBar = new JMenuBar();
setJMenuBar(menuBar);
//trial menu
menu = new JMenu("File");
menu.setMnemonic(KeyEvent.VK_F);
menuBar.add(menu);
//trial menu item
menuItem = new JMenuItem("Quit");
menuItem.setMnemonic(KeyEvent.VK_Q);
menu.add(menuItem);
//trial row panel
JPanel row = new JPanel(new GridLayout(6,4,5,10));
row.add(lblregistry);
txtregistry.setEditable(false);
row.add(txtregistry);
row.add(lblfirstName);
txtfirstName.setEditable(false);
row.add(txtfirstName);
row.add(lbllastName);
txtlastName.setEditable(false);
row.add(txtlastName);
row.add(lblmiddleName);
txtmiddleName.setEditable(false);
row.add(txtmiddleName);
row.add(lblgender);
txtgender.setEditable(false);
row.add(txtgender);
row.add(lblbirthDate);
txtbirthDate.setEditable(false);
row.add(txtbirthDate);
row.add(lblbirthType);
txtbirthType.setEditable(false);
row.add(txtbirthType);
row.add(lblmultiBirth);
txtmultiBirth.setEditable(false);
row.add(txtmultiBirth);
row.add(lblbirthOrder);
txtbirthOrder.setEditable(false);
row.add(txtbirthOrder);
row.add(lblbirthWeight);
txtbirthWeight.setEditable(false);
row.add(txtbirthWeight);
gui.add(row, BorderLayout.NORTH);
JPanel buttonPanel = new JPanel(new BorderLayout(3,3));
gui.add(buttonPanel,BorderLayout.WEST);
JPanel btn = new JPanel(new GridLayout(6,1,5,5));
btn.add(newData);
btn.add(updateData);
btn.add(deleteData);
btn.add(printData);
buttonPanel.add(btn);
}
#SuppressWarnings("unchecked")
private void tbData(){
try{
stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
String sql = "SELECT ChildID, FirstName, LastName, MiddleName FROM childinfo";
rs = stmt.executeQuery(sql);
ResultSetMetaData md = rs.getMetaData();
int columns = md.getColumnCount();
for(int i = 1; i <= columns; ++i){
columnNames.add(md.getColumnName(i));
}
while(rs.next()){
#SuppressWarnings("rawtypes")
Vector row = new Vector(columns);
for(int i = 1; i<= columns; i++){
row.addElement(rs.getObject(i));
}
data.addElement(row);
}
rs.close();
stmt.close();
}
catch(SQLException e){
JOptionPane.showMessageDialog(MainForm.this, e.getMessage());
}
DefaultTableModel model = new DefaultTableModel(data,columnNames);
JTable table = new JTable(model){
#SuppressWarnings({ "rawtypes" })
public Class getColumnClass(int column){
for(int row = 0; row < getRowCount(); row++){
Object o = getValueAt(row,column);
if(o != null){
return o.getClass();
}
}
return Object.class;
}
};
table.setRowSelectionAllowed(true);
table.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent evt) {
int row = table.getSelectedRow();
try{
String dataClick = (table.getModel().getValueAt(row, 0).toString());
stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
String sql = "SELECT * FROM childinfo WHERE ChildID='"+dataClick+"'";
rs = stmt.executeQuery(sql);
if(rs.next()){
txtregistry.setText(Integer.toString(rs.getInt("ChildID"))); *this is where i get the error*
txtfirstName.setText(rs.getString("FirstName"));
txtlastName.setText(rs.getString("LastName"));
txtmiddleName.setText(rs.getString("MiddleName"));
txtgender.setText(rs.getString("Gender"));
txtbirthDate.setText(rs.getString("BirthDate"));
txtbirthType.setText(rs.getString("BirthType"));
txtmultiBirth.setText(rs.getString("IfMultiBirth"));
txtbirthOrder.setText(Integer.toString(rs.getInt("BirthOrder")));
txtbirthWeight.setText(Integer.toString(rs.getInt("BirthWeight")));
}
}
catch(SQLException er){
JOptionPane.showMessageDialog(MainForm.this, er.getMessage());
}
}
});
JScrollPane scrollPane = new JScrollPane(table);
gui.add(scrollPane, BorderLayout.CENTER);
}
private void setLookAndFeel(){
try{
UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
}
catch(Exception ee){
}
}
JTextField txtfirstName;
JTextField txtlastName;
JTextField txtmiddleName;
JTextField txtbirthDate;
JTextField txtgender;
JTextField txtbirthType;
JTextField txtmultiBirth;
JTextField txtbirthOrder;
JTextField txtbirthWeight;
JTextField txtregistry;
JTable table;
Kindly help me to fix the problem.
You're shadowing all the variable names for the components used in your class. E.g. Replace
JTextField txtfirstName = new JTextField();
with
txtfirstName = new JTextField();
I am getting a bunch of error when I try to insert a new data to the table (Type data for each field and then click submit). It supposed to output the SQL insertion command (exactly the same on that used by Java) in the TextArea. How can I fix this problem? Am I missing something in my code? Here is my code:
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
import javax.swing.*;
//This GUI interface is a place holder to be finished by students.
public class InsertPanel extends JPanel{
private Connection connection = null;
private Statement statement = null;
public JTextField isbnTextFld;
public JTextField authorTextFld;
public JTextField titleTextFld;
public JTextField priceTextFld;
public JTextArea textArea;
public JButton submitBtn;
public InsertPanel() {
setBackground(Color.yellow);
setPreferredSize(new Dimension(540, 500));
JPanel p = new JPanel();
p.setLayout(new GridLayout(5, 3));
JLabel isbnLabel = new JLabel("ISBN: ");
isbnTextFld = new JTextField(10);
JLabel authorLabel = new JLabel("Author: ");
authorTextFld = new JTextField(15);
JLabel titleLabel = new JLabel("Title: ");
titleTextFld = new JTextField(20);
JLabel priceLabel = new JLabel("Price: ");
priceTextFld = new JTextField(10);
submitBtn = new JButton("Submit");
ButtonListener buttonListener = new ButtonListener();
submitBtn.addActionListener(buttonListener);
textArea = new JTextArea(10, 30);
p.add(isbnLabel);
p.add(isbnTextFld);
p.add(authorLabel);
p.add(authorTextFld);
p.add(titleLabel);
p.add(titleTextFld);
p.add(priceLabel);
p.add(priceTextFld);
p.add(submitBtn);
p.add(textArea);
add(p, BorderLayout.NORTH);
add(textArea, BorderLayout.CENTER);
}
public class ButtonListener implements ActionListener{
public void actionPerformed(ActionEvent e){
try {
connection = DriverManager.getConnection(
"jdbc:mysql://localhost/books", "root", "admin");
statement = connection.createStatement();
String isbn = isbnTextFld.getText();
String title = titleTextFld.getText();
String author = authorTextFld.getText();
String price = priceTextFld.getText();
String sql = "Insert('" + (isbn) + "' + '" + (title) + "' + '" + (author) + "' + '" + (price)
+ "')";
statement.executeUpdate(sql);
} catch (SQLException sqlException){
sqlException.printStackTrace();
}
}
}
}
create table books
( isbn char(13) not null primary key,
author char(30),
title char(60),
price float(4,2)
);
insert into books values
("0-672-31697-8", "Michael Morgan", "Java 2 for Professional Developers", 34.99),
("0-672-31745-1", "Thomas Down", "Installing Debian GNU/Linux", 24.99),
("0-672-31509-2", "Pruitt, et al.", "Teach Yourself GIMP in 24 Hours", 24.99),
("0-672-31769-9", "Thomas Schenk", "Caldera OpenLinux System Administration Unleashed", 49.99);
Thanks for your hepl!!!
My first suggestion is that you should learn more SQL Syntax before attempting further. I am stating this because the valid SQL insert statement should look like:
INSERT INTO <table_name> VALUES (<value1>, <value2>, ....);
OR
INSERT INTO <table_name> (<column_1>, <column_2>, ...) VALUES (<value1>, <value2>, ....);
Also you should try to use PreparedStatement instead of Statement to dynamically set the values to the statement. And go through JDBC in details.
I am retrieving details from table made in MS Access Database.
User enters some name
(being same name as present in table) in Textfield , then by hitting on submit button, details like FName,Studentid,Branch,Year,Semester,Email and Contact No is displayed.
My Java File is getting compiled correctly, but fetching details from table is not successfull.
The code is:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.sql.*;
import java.io.*;
class Data extends JFrame
{
JFrame f;
JTabbedPane t;
Data()
{
f = new JFrame("Data");
f.setBounds(0,0,1300,500);
t = new JTabbedPane();
t.addTab("View", new View());
f.add(t);
f.setVisible(true);
f.setDefaultCloseOperation(f.EXIT_ON_CLOSE);
}
public static void main(String args[])
{
Data data = new Data();
}
}
class View extends JPanel implements ActionListener
{
JLabel id,l1,l2,l3,l4,l5,l6,l7,l8,l9,l10,l11,l12;
JButton b1;
JTextField tf1;
JPanel p1,p2;
View()
{
setLayout(null);
p1 = new JPanel();
p1.setBounds(0,0,1300,100);
p1.setBackground(Color.red);
p2 = new JPanel();
p2.setLayout(null);
p2.setBounds(0,100,1300,400);
p2.setBackground(Color.blue);
id=new JLabel("Student Name");
id.setBounds(500,100,100,50);
b1=new JButton("SUBMIT");
b1.setBounds(600,150,100,50);
tf1=new JTextField(20);
tf1.setBounds(600,100,100,50);
p1.add(id);
p1.add(tf1);
b1.addActionListener(this);
p1.add(b1);
add(p1);
add(p2);
l1=new JLabel();
l2=new JLabel();
l3=new JLabel();
l4=new JLabel();
l5=new JLabel();
l6 = new JLabel();
l7=new JLabel("FName");
l8=new JLabel("Branch");
l9=new JLabel("Year");
l10=new JLabel("Semester");
l11=new JLabel("Email");
l12=new JLabel("Contact No");
l1.setBounds(700,10,100,20);
l2.setBounds(700,40,100,20);
l3.setBounds(700,70,100,20);
l4.setBounds(700,100,100,20);
l5.setBounds(700,130,100,20);
l6.setBounds(700,160,100,20);
l7.setBounds(500,10,100,20);
l8.setBounds(500,40,100,20);
l9.setBounds(500,70,100,20);
l10.setBounds(500,100,100,20);
l11.setBounds(500,130,100,20);
l12.setBounds(500,160,100,20);
p2.add(l1);
p2.add(l2);
p2.add(l3);
p2.add(l4);
p2.add(l5);
p2.add(l6);
p2.add(l7);
p2.add(l8);
p2.add(l9);
p2.add(l10);
p2.add(l11);
p2.add(l12);
p1.setVisible(true);
p2.setVisible(true);
}
public void actionPerformed(ActionEvent ae)
{
String nm="0",br="0",yr ="0",sm="0",em="0",ph="0";
int p=0;
if(ae.getSource()==b1)
{
try
{
String ss=tf1.getText();
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection("JDBC:ODBC:MS Access Database","","");
Statement st=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
ResultSet rs=st.executeQuery("Select * from information where FName= "+ss+" ");
System.out.println(rs);
while(rs.next())
{
nm=rs.getString("FName");
br=rs.getString("Branch");
yr=rs.getString("Year");
sm=rs.getString("Semester");
em=rs.getString("Email");
ph=rs.getString("Contact No");
p=Integer.parseInt(ph);
l1.setText(nm);
l2.setText(br);
l3.setText(yr);
l4.setText(sm);
l5.setText(em);
l6.setText(ph);
}
con.close();
}
catch(Exception e)
{
}
}
}
}
Please help what is wrong in code.....
When you "glued together" your SQL statement you didn't put any quotes around the string value in the WHERE clause. However, you shouldn't be "gluing together" SQL statements anyway. You should be using a parameter query, something like this
PreparedStatement st = con.prepareStatement(
"Select * from information where FName=?",
ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
st.setString(1, ss);
ResultSet rs = st.executeQuery();