基本操作
package jdbc; import java.sql.Statement; import java.util.Scanner; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; public class test { public static void main(String[] args) throws Exception { String url = "jdbc:mysql://localhost:3306/usedb" ; //下面几行都是模板 String user = "root" ; String password = "" ; Class.forName("com.mysql.jdbc.Driver"); Connection conn=DriverManager.getConnection(url, user, password); Statement stmt=conn.createStatement(); String sql="select * from myuser"; //sql语句 ResultSet re=stmt.executeQuery(sql); //传入sql语句获得结果集 while(re.next()){ //next函数 System.out.println(re.getString("name")); //得到特定字段对应的值 String s1=re.getString(1); //得到第几个字段对应的值,不一定是String 类型 String s2=re.getString(2); System.out.println(s1+" "+s2); } sql="insert into myuser values('4','lihua','122222')"; //修改语句 int i=stmt.executeUpdate(sql);//可实现添加删除修改,返回int值,代表影响几条记录 if(i==1) System.out.println("添加成功"); else System.out.println("添加失败"); re.close(); stmt.close(); conn.close(); } }
PreparedStatement
Connection conn=DriverManager.getConnection(url, user, password); PreparedStatement ps=null; ps=conn.prepareStatement("select name from myuser where id=?"); //这种方式更佳 ps.setString(1, "1"); //设置第几个问号为什么 ResultSet re=ps.executeQuery(); //执行sql语句 while(re.next()){ //next函数 String s=re.getString(1); System.out.println(s); //得到特定字段对应的值 }