473,378 Members | 1,555 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,378 software developers and data experts.

Mysql

PLEASE HELP ME WITH MY CODE??


import java.sql.*;
import java.io.*;

class min_filmdb_rel_mysql {
public static void main (String args [])
throws SQLException, IOException {

// the following statement loads the MySQL jdbc driver

try {
Class.forName ("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
System.out.println ("Could not load the driver");
}

String user, pass, host;
user = readEntry("userid: ");
pass = readEntry("password: ");
host = readEntry("hostname or ip address: ");
// userid, password and hostname are obtained from the console

Connection conn = DriverManager.getConnection
("jdbc:mysql://"+host+":3306/test", user, pass);

/* JDBC default is to commit each SQL statement as it is sent to the database. Setting autocommmit=false changes the default
behaviour so that transactions have to be committed explicity.
*/
conn.setAutoCommit(false);

// Creating a statement lets us issue commands against the connection.

Statement s = conn.createStatement();

// Creating and populating Customer table

s.executeUpdate("create table IF NOT EXISTS Customer( CustomerID VARCHAR(20) PRIMARY KEY, FirstName VARCHAR(20), Surname VARCHAR(20), Address VARCHAR(30), Post code VARCHAR(7), Telephone No VARCHAR(15), Email VARCHAR(20))");
System.out.println("Created table Customer");

s.executeUpdate("insert into Customer values('George Clooney', 'Male', 'American', Date'1965-12-04','Casualty')");

conn.commit();
System.out.println("Inserted some Customers");



ResultSet result=s.executeQuery("Select * From Customer");
System.out.println("Results: ");
while(result.next()) {
System.out.println(result.getString(1) +" "+ result.getString(2) + " "+result.getString(3) +" "+ result.getString(4)+" "+ result.getString(5) );

// Creating and populating Supplier table

s.executeUpdate("create table IF NOT EXISTS Supplier( SupplierID VARCHAR(20) PRIMARY KEY, SupplierName VARCHAR(20), Address VARCHAR(20), Post code VARCHAR(7), Telephone No VARCHAR(15), Email VARCHAR(20))");
System.out.println("Created table Supplier");

// Creating and populating Product table

s.executeUpdate("create table IF NOT EXISTS Product( ProductID VARCHAR(20) PRIMARY KEY, SupplierID VARCHAR(20) PRIMARY KEY, ProductName VARCHAR(20), Price VARCHAR(20))");
System.out.println("Created table Product");

// Creating and populating Staff table

s.executeUpdate("create table IF NOT EXISTS Staff( StaffID VARCHAR(20) PRIMARY KEY, DeptID VARCHAR(20) PRIMARY KEY, FirstName VARCHAR(20), Surname VARCHAR(20), Address VARCHAR(20), Post code VARCHAR(7), Telephone No VARCHAR(15), Mobile No VARCHAR(11))");
System.out.println("Created table Staff");

// Creating and populating Department table

s.executeUpdate("create table IF NOT EXISTS Department( DeptID VARCHAR(20) PRIMARY KEY, DeptName VARCHAR(20))");
System.out.println("Created table Department");

// Creating and populating Customer_Order table

s.executeUpdate("create table IF NOT EXISTS Customer_Order( CustomerID VARCHAR(20) PRIMARY KEY, OrderID VARCHAR(20) PRIMARY KEY, ProductID VARCHAR(20) PRIMARY KEY, ProductName VARCHAR(20), Qty VARCHAR(10), Price VARCHAR(10), Paid VARCHAR(10))");
System.out.println("Created table Cutomer_Order");

// Creating and populating Supplier_Order table

s.executeUpdate("create table IF NOT EXISTS Supplier_Order( SupplierID VARCHAR(20) PRIMARY KEY, OrderID VARCHAR(20) PRIMARY KEY, ProductID VARCHAR(20) PRIMARY KEY, ProductName VARCHAR(20), Qty VARCHAR(10), Price VARCHAR(10))");
System.out.println("Created table Supplier_Order");

s.executeUpdate("insert into Customer values('George Clooney', 'Male', 'American', Date'1965-12-04','Casualty')");

conn.commit();
System.out.println("Inserted some Customers");



ResultSet result=s.executeQuery("Select * From Customer");
System.out.println("Results: ");
while(result.next()) {
System.out.println(result.getString(1) +" "+ result.getString(2) + " "+result.getString(3) +" "+ result.getString(4)+" "+ result.getString(5) );
}


// We end the transaction and the connection.

conn.commit();


conn.close();
}

//readEntry function -- to read input string

static String readEntry(String prompt) {
try {
StringBuffer buffer = new StringBuffer();
System.out.print(prompt);
System.out.flush();
int c = System.in.read();
while(c != '\n' && c != -1) {
buffer.append((char)c);
c = System.in.read();
}
return buffer.toString().trim();
} catch (IOException e) {
return "";
}
}



class min_filmdb_preparedstatement_mysql {
public static void main (String args [])
throws SQLException, IOException {

// the following statement loads the MySQL jdbc driver

try {
Class.forName ("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
System.out.println ("Could not load the driver");
}

String user, pass, host, database;
user = readEntry("userid : ");
pass = readEntry("password: ");
host = readEntry("hostname or ip address: ");
database = readEntry("database: ");
// userid, password and hostname are obtained from the console

Connection conn = DriverManager.getConnection
("jdbc:mysql://"+host+":3306/"+database, user, pass);

/* JDBC default is to commit each SQL statement as it is sent to the database. Setting autocommmit=false changes the default
behaviour so that transactions have to be committed explicity.
*/
conn.setAutoCommit(false);

// Creating a statement lets us issue commands against the connection.

Statement s = conn.createStatement();

// Creating and populating Actor table

s.executeUpdate("CREATE TABLE IF NOT EXISTS Actor( ActorName VARCHAR(20) PRIMARY KEY, Sex VARCHAR(6), Nationality VARCHAR(20), DOB DATE, DebutFilmTitle VARCHAR(30))");
System.out.println("Created table Actor");

s.executeUpdate("DELETE FROM Actor WHERE TRUE"); // delete all rows from Actor table

// INSERTING DATA USING Statement OBJECT

s.executeUpdate("INSERT INTO Actor VALUES('George Clooney', 'Male', 'American', Date'1965-12-04','Casualty')");
conn.commit();

System.out.println("Inserted one row in Actor table using Statement class");


/* INSERTING DATA USING PreparedStatement OBJECT
*
* The following code is no better than using a Statement object because the PreparedStatement
* object is being compiled twice.
*
*/

String psq = "INSERT INTO Actor VALUES('Hugh Grant', 'Male', 'British', Date'1966-12-04','Four Weddings')";
PreparedStatement ps = conn.prepareStatement(psq); // create PreparedStatement object
ps.execute(); // execute the prepared statement


psq = "INSERT INTO Actor VALUES('Helen Mirren', 'Female', 'British', Date'1945-07-26','The Queen')";
ps = conn.prepareStatement(psq); // create PreparedStatement object
ps.execute(); // execute the prepared statement

conn.commit();

System.out.println("Inserted two rows in Actor table using PreparedStatement class");

/* A PreparedStatement is more useful when it is compiled with a number
of parameters whose value is assigned before the prepared statement is
executed. In the following declaration, each ? stands for a parameter.
*/

String psq2 = "insert into Actor values(?, ?, ?, ?, ?)";
PreparedStatement ps2 = conn.prepareStatement(psq2);

/* Parameter values are set by various setXXX methods of the
PreparedStatement class.

Note how a string is converted to a Java Date before it is used
in the setDate method. (Is there a simpler way?))
*/

ps2.setString(1, "Clark Gable"); // first ? in ps is a String
ps2.setString(2, "Male"); // second ? in ps is a String
ps2.setString(3, "American"); // third ? in ps is a String

// Next line emphasises that it is java.sql.Date and NOT java.util.Date
java.sql.Date when = new java.sql.Date(0); // No default constructor without an argument
when = new java.sql.Date(0).valueOf("1911-06-23"); //convert string in yyyy-mm-dd format to date

ps2.setDate(4,when); // fourth ? in ps is Date
ps2.setString(5, "Gone with the Wind"); // fifth ? in ps is a String

// Now execute the prepared statement to load data

ps2.execute(); // execute the prepared statement

// Clear the parameter values so that they can be set again.
ps2.clearParameters();

// ESSENTIAL JAVA CODE FOR LOADING DATA FROM A TEXT FILE

// We will reuse ps2 which has been compiled previously.

String line; // Data from text file to be read one line at a time

String[] tokens; // line will be parsed into an array of Strings

System.out.println("Inserting data from text file");

String data_file = "data_files/actor_data.txt";

File inputFile = new File(data_file);
FileReader inf = new FileReader(inputFile);
BufferedReader inb = new BufferedReader(inf);

System.out.println("Ready to read line");

line = inb.readLine(); // read a line
// System.out.println(line);

while ( (line != null) ) {
tokens = line.split(","); // split line into tokens separated by a comma

System.out.println(tokens[0]+" "+tokens[1]+" "+tokens[2]+" "+tokens[3]+" "+tokens[04]+" ");

// At this point one should really trim leading and trailing space characters from the tokens.

ps2.setString(1, tokens[0]); // first ? in ps is a String
ps2.setString(2, tokens[1]); // second ? in ps is a String
ps2.setString(3, tokens[2]); // third ? in ps is a String
when = new java.sql.Date(0).valueOf(tokens[3]); //convert string in yyyy-mm-dd format to date
ps2.setDate(4,when); // fourth ? in ps is Date
ps2.setString(5, tokens[4]); // fifth ? in ps is a String
ps2.execute(); // execute the prepared statement
ps2.clearParameters();

line=inb.readLine(); //read next line

}

conn.commit(); // commit after all data has been inserted
inb.close(); // close the buffered reader
inf.close(); // close the file


System.out.println("Inserted some actors using PreparedStatement");



ResultSet result=s.executeQuery("Select * From Actor");
System.out.println("Results: ");
while(result.next()) {
System.out.println(result.getString(1) +" "+ result.getString(2) + " "+result.getString(3) +" "+ result.getString(4)+" "+ result.getString(5) );
}


// We end the transaction and the connection.

conn.commit();


conn.close();
}

//readEntry function -- to read input string
static String readEntry(String prompt) {
try {
StringBuffer buffer = new StringBuffer();
System.out.print(prompt);
System.out.flush();
int c = System.in.read();
while(c != '\n' && c != -1) {
buffer.append((char)c);
c = System.in.read();
}
return buffer.toString().trim();
} catch (IOException e) {
return "";
}
}
} }
Nov 11 '07 #1
1 2506
r035198x
13,262 8TB
1.) Use code tags when posting code.
2.) What is the actual problem then?
Nov 12 '07 #2

Sign in to post your reply or Sign up for a free account.

Similar topics

2
by: francescomoi | last post by:
Hi. I'm trying to build 'MySQL-python-1.2.0' on my Linux FC2: ---------------------------------- # export PATH=$PATH:/usr/local/mysql/bin/ # export mysqlclient=mysqlclient_r # python setup.py...
4
by: mikey | last post by:
Hi all, I'm having great problems trying to install the latest MySQl RPM package onto my Red Hat Linux OS. There is already MySQL v 3.0 pre-installed with the RH Linux distribution disk but I...
0
by: Yun Guan | last post by:
Hello mysql gurus, I am trying to run perl on mysql database on Red Hat box. I want to install DBI and DBD:mysql using CPAN: perl -MCPAN -e shell cpan>install DBI The above succeeded, but...
0
by: Mike Chirico | last post by:
Interesting Things to Know about MySQL Mike Chirico (mchirico@users.sourceforge.net) Copyright (GPU Free Documentation License) 2004 Last Updated: Mon Jun 7 10:37:28 EDT 2004 The latest...
2
by: Saqib Ali | last post by:
I installed mySQL and have it running.... but I think I made a mistake somewhere along the line...... I believe I did follow the instructions that were provided with the distribution at:...
1
by: Alex Hunsley | last post by:
I am trying to install the DBD::mysql perl module. However, it claims I need mysql.h: cpan> install DBD::mysql CPAN: Storable loaded ok Going to read /home/alex/.cpan/Metadata Database was...
0
by: ./Rob & | last post by:
Hi gang: I'm experiencing a problem with MySQL -- I updated MySQL from version 4.1.0 to 4.1.10 and now when I login as root it doesn't show all the databases I should have access to, nor it...
2
by: trihanhcie | last post by:
I m currently working on a Unix server with a fedora 3 as an os My current version of mysql is 3.23.58. I'd like to upgrade the version to 5.0.18. After downloading from MYSQL.COM the package on...
1
by: manish deshpande | last post by:
Hi, When i'm installing MySQL-server-standard-5.0.24a-0.rhel3.i386.rpm by the following command: rpm -i MySQL-server-standard-5.0.24a-0.rhel3.i386.rpm the following error is being shown: ...
3
by: menzies | last post by:
Hi, I"m new to this forum, but I have been trying all day to install DBD::mysql onto my Intel MacBook. I've read lots of forums pages and none have gotten me to a successful 'make test' or a...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.