package Dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class MySql {

private String url = "jdbc:mysql://localhost:3306/jw?useUnicode=true&characterEncoding=utf-8";
private String user = "root";
private String password = "root";
public Connection getCon(){
Connection conn = null;
try{
Connection con = DriverManager.getConnection(url , user , password ) ;
}catch(SQLException se){
System.out.println("数据库连接失败!");
se.printStackTrace() ;
}
return conn;
}
public void Query(String sql){
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
//建立数据库连接
conn =getCon();
stmt = conn.createStatement();//创建一个Statement对象
System.out.println("成功连接到数据库~");

/*在询数据表时,需要用到ResultSet接口,它类似于一个数据表,通过该接口的实例
* 可以获得检索结果集,以及对应数据表的接口信息。*/
rs = stmt.executeQuery(sql);//创建数据对象

//遍历查询的结果集
while (rs.next()) {
System.out.print(rs.getInt(1)+"\t");
System.out.print(rs.getString(2)+"\t");
System.out.print(rs.getString(3)+"\t");
System.out.print(rs.getString(4)+"\t");
System.out.println();
}
//关闭连接
rs.close();
stmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
public void insert(String sql){
Connection conn = null;
PreparedStatement pstm = null;
ResultSet rt = null;
Statement stmt = null;
//建立数据库连接
try {
conn =getCon();
//String sql = "INSERT INTO comments(MovieName,Mid,Mnum,url,content,date,star,usefulnum) VALUES(?,?,?,?,?,?,?,?)";
//pstm.setString(1, n.getMovieName());
//pstm.setString(2, n.getMid());
pstm = conn.prepareStatement(sql);
pstm.executeUpdate();

String sql3 = "select * from users";//要执行的SQL

/*在询数据表时,需要用到ResultSet接口,它类似于一个数据表,通过该接口的实例
* 可以获得检索结果集,以及对应数据表的接口信息。*/
ResultSet rs = stmt.executeQuery(sql3);//创建数据对象

System.out.println("编 号"+"\t"+"姓 名"+"\t"+"密 码"+"\t"+"邮 箱");
//遍历查询的结果集
while (rs.next()) {
System.out.print(rs.getInt(1)+"\t");
System.out.print(rs.getString(2)+"\t");
System.out.print(rs.getString(3)+"\t");
System.out.print(rs.getString(4)+"\t");
System.out.println();
}
//关闭连接
rs.close();
stmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
public void Delete(String sql){
Connection conn = null;
PreparedStatement psql = null;
//建立数据库连接
try {
conn =getCon();
psql = conn.prepareStatement(sql);
psql.executeUpdate();
psql.close();
}catch(SQLException e){
e.printStackTrace();
}catch (Exception e) {
e.printStackTrace();
}finally{
System.out.println("数据库数据删除成功!"+"\n");
}
}

}

posted on 2018-05-16 21:47  ALT_LB  阅读(192)  评论(0编辑  收藏  举报