
且预先出入三条记录:
1 Jack
2 John 91
3 Mike 99
具体代码如下:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class TestConn {
private static final String username = "root";
private static final String password = "123456";
private static final String mysql = "jdbc:mysql://localhost/tss";
private static Connection conn = null;
private static Statement stmt = null;
private static ResultSet rs = null;
private static String sql = "";
private static String sname;
private static int score;
public static void main(String[] args) throws ClassNotFoundException {
try {
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Successfully download JDBC!");
conn = DriverManager.getConnection(mysql, username, password);
System.out.println("Successfully connect to DB!");
} catch (SQLException e) {
System.err.println(e.getMessage());
}
try {
stmt = conn.createStatement();
} catch (SQLException e) {
e.printStackTrace();
}
sql = "select * from student";
try {
rs = stmt.executeQuery(sql);
} catch (SQLException e1) {
e1.printStackTrace();
}
try {
while(rs.next()){
sname = rs.getString("sname");
score = rs.getInt("score");
System.out.println(sname + ": " + score);
}
} catch (SQLException e1) {
e1.printStackTrace();
}
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
运行结果如下;
Jack:
John: 91
Mike: 99
