java--java连接数据库

package cn.hncu;


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


//import com.mysql.jdbc.Driver;
//myelipese补全的方式输入Driver类即可得该import语句(连接串)



public class DbHelloWorld {

    public static void main(String[] args) {
//      Driver
        try {
            //加载连接器--1)网上查找。2)用Driver类补全方式获得连接串(com.mysql.jdbc.Driver)
            Class.forName("com.mysql.jdbc.Driver");//驱动
            //申明连接哪个数据库,同时指定编码
//          String url="jdbc:mysql:///:3306/hncu?useUnicode=true&&characterEncoding=UTF-8";//“/”也可以代表本机
            String url="jdbc:mysql://127.0.0.1:3306/hncu?useUnicode=true&&characterEncoding=UTF-8";//完整方式
            //127.0.0.1本机,3306端口号,hncu数据库。useUnicode=true&&characterEncoding=UTF-8(参数)指定编码
            //建立连接
            Connection con=DriverManager.getConnection(url, "root", "1234");
            //对数据库内容进行操作
            Statement st=con.createStatement();//创建语句对象
            //增删改
//          String sql="update stud set score=100 where id='a010'";
//          String sql="insert into stud values('a015','下雪',45.8,16)";
//          String sql="delete from stud where score>90";
//          st.execute(sql);
            //查
            String sql="select * from stud where score>60";
            ResultSet rs=st.executeQuery(sql);//迭代器
            while(rs.next()){//表示有没有移到数据行,有则返回true
                String id=rs.getString(1);//字段序号--从1开始
                String id2=rs.getString("id");//字段名
                String name=rs.getString("name");//字段名
                Double score=rs.getDouble("score");//字段名
                Integer age=rs.getInt(4);//字段序号--从1开始
                System.out.println(id+","+id2+","+name+","+score+","+age);
            }

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }catch (SQLException e) {
            e.printStackTrace();
        }
    }

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章