import java.sql.*;
/**
* @version 2015-03-19
* 与MYSQL连接后,执行插入数据的操作
*/
public class InsertDemo {
public static void main(String[] args) throws SQLException {
Connection conn = null;
Statement stmt = null;
try {
//第一步:加载MySQL的JDBC的驱动
Class.forName("com.mysql.jdbc.Driver");
System.out.println("加载驱动成功!");
//取得连接的url,能访问MySQL数据库的用户名,密码;数据库名 :test
String url = "jdbc:mysql://localhost:3306/test?"
+ "user=root&password=root&useUnicode=true&characterEncoding=UTF8";
String username = "root";
String password = "root";
//第二步:创建与MySQL数据库的连接类的实例
conn = DriverManager.getConnection(url, username, password);
//创造SQL语句
String sql = "INSERT INTO student ( no, name ) VALUES ( '2010101592', '刘博' )";
// 执行SQL语句
stmt = conn.createStatement();
stmt.executeUpdate(sql);
System.out.println("插入数据成功");
} catch (Exception e) {
e.printStackTrace();
stmt.close();
conn.close();
}
}
} |
|