Create a Java project and a package called de.vogella.mysql.first.
Create a lib
folder and copy the JDBC driver into this folder. Add the JDBC driver to your classpath. See Adding jars to the classpath for details.
Create the following class to connect to the MySQL database and perform queries, inserts and deletes. It also prints the metadata [table name, column names] of a query result.
package de.vogella.mysql.first;
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 java.util.Date;
public class MySQLAccess {
private Connection connect = null;
private Statement statement = null;
private PreparedStatement preparedStatement = null;
private ResultSet resultSet = null;
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[];
// Result set get the result of the SQL query
resultSet = statement
.executeQuery["select * from feedback.comments"];
writeResultSet[resultSet];
// 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, "Test"];
preparedStatement.setString[2, "TestEmail"];
preparedStatement.setString[3, "TestWebpage"];
preparedStatement.setDate[4, new java.sql.Date[2009, 12, 11]];
preparedStatement.setString[5, "TestSummary"];
preparedStatement.setString[6, "TestComment"];
preparedStatement.executeUpdate[];
preparedStatement = connect
.prepareStatement["SELECT myuser, webpage, datum, summary, COMMENTS from feedback.comments"];
resultSet = preparedStatement.executeQuery[];
writeResultSet[resultSet];
// Remove again the insert comment
preparedStatement = connect
.prepareStatement["delete from feedback.comments where myuser= ? ; "];
preparedStatement.setString[1, "Test"];
preparedStatement.executeUpdate[];
resultSet = statement
.executeQuery["select * from feedback.comments"];
writeMetaData[resultSet];
} catch [Exception e] {
throw e;
} finally {
close[];
}
}
private void writeMetaData[ResultSet resultSet] throws SQLException {
// Now get some metadata from the database
// Result set get the result of the SQL query
System.out.println["The columns in the table are: "];
System.out.println["Table: " + resultSet.getMetaData[].getTableName[1]];
for [int i = 1; i