Add multiple rows in Oracle using Java - java

I have a text field and a button. When i enter data and click button it adds only one row.
public void widgetSelected(SelectionEvent e) {
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:xe","system","nikshay");
Statement stmt=con.createStatement();
stmt.executeUpdate("create table sbase(person varchar(20),year number(2),gender varchar(1))");
PreparedStatement prepare=con.prepareStatement("insert into sbase (person,year,gender)values(?,?,?)");
prepare.setString(1,text.getText());
prepare.setString(2,text_1.getText());
prepare.setString(3,text_2.getText());
prepare.executeUpdate();
}
catch(Exception ex)
{
}
}
What should I do to add multiple rows.

Related

Error getting value from jdatechooser and adding it to database java

How can I show jcalender?
How to get the selected value from it and add it to database?
From google I found a file called jcalender-1.4. I've added it to the jframe but when I try to get selected value from it and add it to the database it shows error. Table is created but error shows while inserting values. The exception in insertion method is shown. I've tried to print the value the value of db9 by commenting the insertData method and it shows null. Below is the link of JCalender jar file that i've used.
https://www.dropbox.com/s/yxe86ylfm4u6be8/jcalendar-1.4.jar?dl=0
JButton btnNewButton = new JButton("New Reservation");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
db1=textField.getText();
db2=textField_1.getText();
db3=textField_2.getText();
db4=textField_3.getText();
db5=textField_4.getText();
db6=textField_5.getText();
db7=textField_6.getText();
db8=(String)comboBox.getSelectedItem();
db9=dateChooser.getDate();
db10=textField_7.getText();
db11=(String)comboBox_1.getSelectedItem();
db12=(String)comboBox_2.getSelectedItem();
db13=dateChooser_1.getDate();
db14=dateChooser_2.getDate();
try {
insertData();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
public static void createTable() throws Exception{
try{
Connection con=getConnection();
PreparedStatement create =con.prepareStatement("CREATE TABLE IF NOT EXISTS hotelDetails(_id INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT,name varchar(65),"
+ "surname varchar(65),address varchar(65),cnic varchar(65),mobileNo varchar(65),email varchar(65),city varchar(65),gender varchar(65),dob Date,country varchar(65),roomType varchar(65),"
+ "roomNo varchar(65),checkin Date,checkout Date)");
create.executeUpdate();
System.out.println("Table Created");
}catch(Exception e)
{
JOptionPane.showMessageDialog(null,"Table Not Created.Try Again","Error", JOptionPane.ERROR_MESSAGE);
}
} public static void insertData() throws Exception{
try{
Connection con=getConnection();
PreparedStatement posted=con.prepareStatement("INSERT INTO hotelDetails(name,surname,address,cnic,mobileNo,email,city,gender,dob,country,roomType,roomNo,checkin,checkout)VALUES('"+db1+"','"+db2+"','"+db3+"','"+db4+"','"+db5+"','"+db6+"','"+db7+"','"+db8+"','"+db9+"','"+db10+"','"+db11+"','"+db12+"','"+db13+"','"+db14+"')");
posted.executeUpdate();
System.out.println("Values Inserted");
}catch(Exception e)
{
JOptionPane.showMessageDialog(null,"Can't Insert Data","Error", JOptionPane.ERROR_MESSAGE);
}
}

How can I make my program display the user's name from the database in JtextField?

I'm making a program where you login and it takes you into a into a different frame after you log in.. That part of the program works, but I'm having trouble getting it to return the user's name and other data from the database. It connects to the database, but it won't return the information inside JTextField. If I can find out how to do firstName, I can figure out the rest. I'm using Eclipse as my IDE and SQLite Manager as the database.
There are 2 tables
Login (username,password)
Student(SID,firstName,GradeLevel, and more)
Also username is there ID start with an S (like S01 and so forth).
Here's the code.
public class student extends JFrame {
private JTextField textField;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
student frame = new student();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
private void ShowInfo() {
try{
String query="SELECT firstName From Student,Login Where firstname=?";
PreparedStatement ps=conn.prepareStatement(query);
ps.setString(1, "firstName");
ResultSet rs= ps.executeQuery();
while (rs.next()) {
textField.setText(rs.getString("firstName"));
System.out.print(""+textField);
}ps.close();
conn.close();
} catch ( Exception ex)
{
JOptionPane.showMessageDialog(null,ex);
}
}
}
private void ShowInfo() {
try{
String query="SELECT firstName From Student,Login Where firstname=?";
PreparedStatement ps=conn.prepareStatement(query);
ps.setString(1, "firstName");
ResultSet rs= ps.executeQuery();
if(rs.next()) {
textField.setText(rs.getString(1));
System.out.print(""+textField); //you are getting data
}ps.close();
conn.close();
} catch ( Exception ex)
{
JOptionPane.showMessageDialog(null,ex); //you have a error
}
}
there were sevral thing which were wrong in the code. first one is there should be something wrong with sql statment Student,Login Where firstname.
you should change this line textField.setText(rs.getString(1));
and you have a while loop to extract the data but and you are planning on having a textfield to store data. that is pointless if you are expecting more than one output from your resultset you need something more than a jtextfield maybe a jtable. bt i have changed your while loop to a if loop to get one single output from the resultset.and the other thing i notice in your application is you are not calling the showInfo method.

java how to use a variable in method from another method

I have tried something like that : but the error appears:
SEVERE: null
null
com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Column 'MYUSER' cannot be null
while it shouldn't? Also I would like to ask if there are some bad practices in my program.
any tips?
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
public class Main extends JFrame {
String text;
public Main() throws HeadlessException {
//opis
JLabel opis = new JLabel("Opis: ");
JTextField opisTextField = new JTextField();
opisTextField.setPreferredSize(new Dimension(100, 20));
add(opis);
add(opisTextField);
//jak klikniemy w przycisk program doda wartosci wpisane do bazy danych.
Button z = new Button("Dodaj do bazy danych");
add(z);
z.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e){}
#Override
public void mouseEntered(MouseEvent e){}
#Override
public void mouseExited(MouseEvent e){}
#Override
public void mouseReleased(MouseEvent e){}
#Override
public void mousePressed(MouseEvent e) {
Main m = new Main();
m.text = opisTextField.getText();
});
}
public void readDataBase() throws Exception {
try {
// this will load the MySQL driver, each DB has its own driver
Class.forName("com.mysql.jdbc.Driver");
// setup the connection with the DB.
connect = DriverManager
.getConnection("jdbc:mysql://localhost/feedback?"
+ "user=sqluser&password=sqluserpw");
// statements allow to issue SQL queries to the database
statement = connect.createStatement();
// resultSet gets the result of the SQL query
// preparedStatements can use variables and are more efficient
preparedStatement = connect
.prepareStatement("insert into FEEDBACK.COMMENTS values (default, ?, ?, ?, ? , ?, ?)");
// "myuser, webpage, datum, summary, COMMENTS from FEEDBACK.COMMENTS");
// parameters start with 1
preparedStatement.setString(1, text);
preparedStatement.executeUpdate();
// remove again the insert comment
} catch (ClassNotFoundException | SQLException e) {
throw e;
} finally {
// close();
}
}
public static void main(String[] args) throws Exception {
new Main().setVisible(true);
}
}
Sorry could not go through all the code but it looks like you declared String text; and you never provided it a value and you are passing this value to username preparedStatement.setString(1, text); which cannot be null as per error.

passing data from one frame and setting it in textfield in another frame retrieving corresponding data from database

I am working on a NetBeans project (Java Swings) using MySQL # the back ground. Got struck in this particular scenario.
I am working with a JTable in one frame, say frame1 from where a row has to be selected on 'onclick' action event.
The corresponding data from the table in background in mysql will be retrieved and the data to be passed on to another frame, say frame2 where the data will be set to a JTextField.
The table in frame1 contains only a few selected tuples of the whole table maintained in the database.
The following are the code snippets i used
::
database table name DB_table
1- Select the data from the table in frame1
public static String Table;
public static int row;
private void jTable1MouseClicked(java.awt.event.MouseEvent evt)
{
// TODO add your handling code here:
jButton3.setEnabled(true);
row = jTable1.getSelectedRow();
Table = (jTable1.getModel().getValueAt(row,0).toString());
}
2- The action event on the button to redirect it to frame2
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt)
{
// TODO add your handling code here:
frame2 ac =new frame2();
jDesktopPane1.add(ac);
try {
ac.setSelectedRow(Table);
} catch (Exception e) {
// Logger.getLogger(showp1.class.getName()).log(Level.SEVERE, null, ex);
}
ac.setVisible(true);
}
3- this is the method in frame2
void setSelectedRow(String Table) {
try {
//ResultSet resultSet = null;
System.out.print(Table);
rs = pst.executeQuery("SELECT * FROM DB_Table where attr="+ Table +"");
//System.out.print(Table);
while (rs.next()) {
System.out.print(Table);
//jTextField1.setText(resultSet.getString(1));
//System.out.print(Table);
jTextField1.setText(rs.getString("attr"));
}
} catch (SQLException ex) {
Logger.getLogger(AddClient.class.getName()).log(Level.SEVERE, null, ex);
}
}
The data is being printed in the output console but not being stored in the text field in frame2...
Hope I am clear with the problem
Any suggestions will be very much appreciated..

Problem in updating database (jdbc)

I'm developing an application in which I dynamically create forms by reading data from a database. What I want is the user to be able to update or delete the database by using the corresponding button in the database(I am allowing user to connect to almost any database so I have no idea about the type of columns, or whether an update will be supported). I've successfully created code to insert data in any database but I am struggling to figure out a way to update and delete records. This is the code snippet for the class for updating/deleting :
/* tflist contains the list of text fields(I used setName() to set their names to
the column names in the table) which I created dynamically
for allowing the user to enter new values and they already hold the
current values,panel contains all the labels and generated gui which is basically
column name in a label and text field,
e.g. Roll no(label) : 9(in a text field),
tablename has the name of the table,
jtable is the table on which event occurred
(you click on a row of table, and a form appears that gives you the option to
update or delete something),and rowno contains the row number of jtable on which
the user clicked */
private void update_buttonActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
String querypart2=" WHERE ";
for(int i=0;i<tflist.size();i++)
{
JTextField tf=tflist.get(i);
if(tf.getText()!=null&&!tf.getText().equals(""))
{
if(jtable.getValueAt(rowno, i)==null||jtable.getValueAt(rowno, i).equals(""))
{
querypart2=querypart2+"\""+tf.getName()+"\" IS NULL";
}
else
{
querypart2=querypart2+"\""+tf.getName()+"\"='"+jtable.getValueAt(rowno,i)+"'";
}
querypart2=querypart2+" AND ";
}
}
if(querypart2.equals(" WHERE "))
{
querypart2="";
}
else
{
querypart2=querypart2.substring(0, querypart2.length()-5);
}
try {
Statement statement = Aw_supersensible.conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ResultSet rs=statement.executeQuery("SELECT * FROM \""+tablename+"\""+querypart2);
rs.absolute(1);
for(int i=0;i<tflist.size();i++)
{
JTextField tf=tflist.get(i);
rs.updateObject(tf.getName(), tf.getText());
}
Aw_supersensible.conn.commit();
for(int i=0;i<tflist.size();i++)
{
JTextField tf=tflist.get(i);
jtable.setValueAt( tf.getText(),rowno,i);
rs.updateRow();
}
central_window.cw.setEnabled(true);
dispose();
}
catch(final Exception e)
{
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new errorWindow(new javax.swing.JFrame(),e.toString()).setVisible(true);
}
});
}
}
private void delete_buttonActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
String querypart2=" WHERE ";
for(int i=0;i<tflist.size();i++)
{
JTextField tf=tflist.get(i);
if(tf.getText()!=null&&!tf.getText().equals(""))
{
if(jtable.getValueAt(rowno, i)==null||jtable.getValueAt(rowno, i).equals(""))
{
querypart2=querypart2+"\""+tf.getName()+"\" IS NULL";
}
else
{
querypart2=querypart2+"\""+tf.getName()+"\"='"+jtable.getValueAt(rowno,i)+"'";
}
querypart2=querypart2+" AND ";
}
}
if(querypart2.equals(" WHERE "))
{
querypart2="";
}
else
{
querypart2=querypart2.substring(0, querypart2.length()-5);
}
try {
Statement statement = Aw_supersensible.conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ResultSet rs=statement.executeQuery("SELECT * FROM \""+tablename+"\""+querypart2);
rs.absolute(1);
rs.deleteRow();
((DefaultTableModel)jtable.getModel()).removeRow(rowno);
Aw_supersensible.conn.commit();
central_window.cw.setEnabled(true);
dispose();
}
catch(final Exception e)
{
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new errorWindow(new javax.swing.JFrame(),e.toString()).setVisible(true);
}
});
}
}
This is some pseudo code for your delete operation, to show you what I think a 'modular' approach would look like.
I am not an experienced developer (in fact I am not a developer), so there may be better ways.
private void delete_buttonActionPerformed(java.awt.event.ActionEvent evt) {
String tableName;
List<String> whereProperties;
List<String> whereValues;
// get your table name
// get your properties and values from the GUI in such a way that the property in whereProperties.get(n) corresponds to the value in whereValues(n)
// have a function in some class (I've called it SQL) that can take the following parameters and performs the delete operation.
SQL.delete(tableName, whereProperties, whereValues);
}

Categories