2014-07-13 16:35:09
来源:中存储网
import java.sql.*;
public class TestDML {
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try {
//第一步:加载MySQL的JDBC的驱动
Class.forName("com.mysql.jdbc.Driver");
//取得连接的 url,能访问MySQL数据库的用户名,密码;数据库名
String url = "jdbc:mysql://localhost:3306/2";
String user = "root";
String password = "19870714";
//第二步:创建与MySQL数据库的连接类的实例
conn = DriverManager.getConnection(url, user, password);
//第三步:用conn创建Statement对象类实例 stmt
stmt = conn.createStatement();
String sql = "insert into student values(3,'jjuan','m')";
stmt.executeUpdate(sql);
} catch (ClassNotFoundException e) {
//加载JDBC错误,所要用的驱动没有找到
System.out.println("驱动加载错误");
}catch (SQLException ex) {
//显示数据库连接错误或查询错误
System.err.println("SQLException:"+ex.getMessage());
}finally {
try{
if(stmt != null) {
stmt.close();
stmt = null;
}
if(conn != null) {
conn.close();
conn = null;
}
}catch(SQLException e)
{
System.err.println("SQLException:"+e.getMessage());
}
}
}
}