Java MySQL Test
January 6, 2012 Leave a comment
First Test
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Example1 {
public static void main(String[] argv) {
Connection conn = null;
try {
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/",
"user","pwd");
} catch (SQLException se) {
System.out.println("Couldn't connect: print out a stack trace and exit.");
se.printStackTrace();
System.exit(1);
}
System.out.println("Connected to database");
if (conn != null)
System.out.println("We connected to the database! Let's select some data.");
else
System.out.println("We should never get here.");
try {
// processing a simple query
Statement st = conn.createStatement();
//by default it fetches all the rows st.setFetchSize(0)
// conn.setAutoCOmmit(false);
// st.setFetchSize(50);
ResultSet rs = st.executeQuery("Select name,tel from test.contact");
while (rs.next()) {
System.out.print("Name=");
System.out.println(rs.getString(1));
System.out.print("Tel=");
System.out.println(rs.getString(2)); }
} catch (SQLException se) {
System.out.println("Couldn't process a query: print out a stack trace and exit.");
se.printStackTrace();
System.exit(1);
}
}
}