连接MySql
时间:2010-10-05 来源:ChangVH
package com.mysql.test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class MyfirstMysql {
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
String name;
String sex;
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
try {
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/tests?user=root&password=root&useUnicode=true&characterEncoding=utf8");
stmt = conn.createStatement();
rs = stmt.executeQuery("select * from b");
while(rs.next()) {
name = rs.getString("sname");
sex = rs.getString("ssex");
System.out.print(name + "\t");
System.out.println(sex);
}
/* String update = "insert into a values('人')";
stmt.executeUpdate(update);
rs = stmt.executeQuery("select * from a");
while(rs.next()) {
name = rs.getString("sname");
System.out.println(name);
}*/
} catch (SQLException ex) {
System.out.println("SQLException: " + ex.getMessage());
System.out.println("SQLState: " + ex.getSQLState());
System.out.println("VendorError: " + ex.getErrorCode());
} finally {
try {
if(conn!=null)
conn.close();
if(rs!=null)
rs.close();
if(stmt!=null)
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}