package org.demo.test;
import java.sql.*;
public class SimpleConnectMysqlDemo {
public static void main(String[] args) {
// 驱动程序名
String driver = "com.mysql.jdbc.Driver";
// URL指向要访问的数据库名scutcs
String url = "jdbc:mysql://127.0.0.1:3306/school?characterEncoding=utf-8";
// MySQL配置时的用户名
String user = "root";
// MySQL配置时的密码
String password = "root";
// 获取当前环境编码
// System.out.println(Charset.defaultCharset());
try {
Class.forName(driver);
// 获取数据库连接
Connection conn = DriverManager.getConnection(url, user, password);
if (!conn.isClosed())
System.out.println("Succeeded connecting to the Database!");
// statement用来执行SQL语句
Statement statement = conn.createStatement();
String sql1 = "select id,username,birthday,image from user";
String hehe ="insert into user( id,username,birthday,image) "
+ "values(NULL,'张三丰','2011/1/1','190.12')";
//String sql2="delete * from table where name='name'";
//String haha="delete * from school where name='张三丰'";
int tag = statement.executeUpdate(hehe);
// 结果集
ResultSet rs = statement.executeQuery(sql1);
while (rs.next()) {
System.out.println(rs.getString("id") +
"\t" + rs.getString("username")+
"\t" + rs.getString("birthday"));
}
// 关闭数据库,释放资源
close(rs, statement, conn);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* 释放资源,释放资源的顺序应该按照释放结果集,释放Statement,释放数据库连接的顺序并且,为了不占用太多的资源,
* 数据库连接建立到释放的时间应该尽量短。
*
* @param rs
* @param st
* @param con
*/
public static void close(ResultSet rs, Statement st, Connection con) {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (st != null) {
try {
st.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (con != null) {
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}