jdbc编程:
要先注册,然后连接,之后传sql语句,查询的话要处理查询结果(一般就是输出),最后一定要释放资源
下面直接上代码和注释
下面代码中,我把密码改成***了。仅供参考
代码
import java.sql.*;
import java.util.Scanner;
public class FirstMySql {
public static void main(String[] args) {
Connection conn=null; //这里是一个数据库连接对象
PreparedStatement ps=null; //这里是一个数据库操作对象
ResultSet rs=null;//用来处理查询结果
try{
Class.forName("com.mysql.jdbc.Driver");//注册驱动
//这里是获取连接(第一个参数3306前固定,后面为database名,第二个为用户名,一般为root,第三个是密码)
conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/bjpowernode","root","***");
//传入sql语句(这里是从员工表中查找工资大于?的,?可以传值)
ps=conn.prepareStatement("select * from emp where sal> ? ");
Scanner s=new Scanner(System.in);
int sal=s.nextInt();
//对?进行赋值
ps.setInt(1,sal);
//执行sql语句,查询结果存入rs
rs=ps.executeQuery();
while(rs.next()){
System.out.printf("%-8s",rs.getString("ename"));
System.out.printf("%4d",rs.getInt("sal"));
System.out.println();
}
} catch (Exception e) {
e.printStackTrace();
}finally{
if(rs!=null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(ps!=null){
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(conn!=null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
查询结果: