第1个回答 2016-08-05
import java.sql.*;
public class Conn {
static Connection con;
static PreparedStatement sql;
static ResultSet res;
public Connection getConnection(){
try {
Class.forName("com.mysql.jdbc.Driver");//需要自己下载
} catch (Exception e) {
e.printStackTrace();
}
try {
con= DriverManager.getConnection("jdbc:mysql://127.0.0.1/dbtest","root","123456"); //需要根据自己的修改
} catch (Exception e) {
e.printStackTrace();
}
return con;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Conn c=new Conn();
c.getConnection();
try {
sql= con.prepareStatement("select * from students");//选择数据表,后面的操作就是根据自己的特殊情况具体实现了
res=sql.executeQuery();
System.out.println("执行增删改前的数据:");
while (res.next()) {
String id=res.getString(1);
String name=res.getString("name");
String age=res.getString("age");
System.out.print("编号"+id+"\t");
System.out.print("姓名"+name+"\t");
System.out.println("年龄"+age+"\t");
}
sql=con.prepareStatement("insert into students values(?,?,?)");
sql.setString(1, "9");
sql.setString(2, "tf");
sql.setString(3, "33");
sql.executeUpdate();
sql=con.prepareStatement("update students set age=?where id='1'");
sql.setString(1, "55");
sql.executeUpdate();
Statement stmt=con.createStatement();
stmt.executeUpdate("delete from students where id='5'");
sql=con.prepareStatement("select * from students");
res=sql.executeQuery();
System.out.println("执行增删改后的数据:");
while (res.next()) {
String id=res.getString(1);
String name=res.getString("name");
String age=res.getString("age");
System.out.print("编号"+id+"\t");
System.out.print("姓名"+name+"\t");
System.out.println("年龄"+age+"\t");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}