MySQL for Linux on POWER 开发应用
2008-01-18 11:06:14 来源:WEB开发网此示例展示的基本代码将连接到 MySQL 数据库并执行查询。
下面是本示例的完整的 Java 代码:
清单 2. Java 代码示例
import java.io.*;
import java.util.*;
import java.sql.*;
public class Java_MySQL
{
public static void display_rs(ResultSet rs) throws SQLException
{
try{
ResultSetMetaData rsmd = rs.getMetaData();
for (int i = 1; i <= rsmd.getColumnCount(); ++i)
System.out.print(" " + (rsmd.getColumnName(i)).toUpperCase() );
System.out.println();
while ( rs.next() )
{
for (int j = 1; j <= rsmd.getColumnCount(); ++j)
{
Object obj = rs.getObject(j);
System.out.print(" " + obj.toString());
}
System.out.println();
}
}
catch (SQLException E) {
System.out.println("SQLException: " + E.getMessage());
System.out.println("SQLState: " + E.getSQLState());
System.out.println("VendorError: " + E.getErrorCode());
E.printStackTrace();
System.exit(1);
}
}
public static void main(String args[])
{
Statement statement = null;
Connection connection = null;
ResultSet resultset;
String query, prompt, input;
int choice = -1;
try {Class.forName("com.mysql.jdbc.Driver").newInstance();}
catch (Exception E) {
System.err.println("Unable to load driver.");
E.printStackTrace();
System.exit(1);
}
try {
String url="jdbc:mysql://localhost/CONTRACTING";
String username="username";
String password="password";
connection=DriverManager.getConnection(url, username, password);
}
catch (SQLException E) {
System.out.println("SQLException: " + E.getMessage());
System.out.println("SQLState: " + E.getSQLState());
System.out.println("VendorError: " + E.getErrorCode());
E.printStackTrace();
connection=null;
System.exit(1);
}
prompt = "
1. Show contents of the table JOB
" +
" 2. Exit
";
while(true)
{
System.out.println(prompt);
try {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
input = in.readLine();
choice = Integer.parseInt(input);
}
catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
try {
switch (choice)
{
case 1:
query="SELECT * FROM JOB;";
statement = connection.createStatement();
resultset = statement.executeQuery(query);
display_rs(resultset);
break;
case 2:
System.out.println("Bye!");
System.exit(0);
default:
System.err.println("Invalid value entered!");
}
}
catch (SQLException E) {
System.out.println("SQLException: " + E.getMessage());
System.out.println("SQLState: " + E.getSQLState());
System.out.println("VendorError: " + E.getErrorCode());
E.printStackTrace();
connection=null;
System.exit(1);
}
}
}
}
更多精彩
赞助商链接