Java中测试数据库连接

首先要有MySQL,然后在MySQL中创建数据库,SQL代码如下:

create database user;                     //创建数据库

use user;                               //使用数据库user

create table tb_userinfo(

id int primary key not null identity(1,1),    //自动+1,主键,不为空!

name char(20) unique,               //char(20) 不重复!

age int check(age>10),        //int类型,年龄必须大于10,否则会出现错误!

sex char(2)                       

)


建立一个Java类文件(之前要在项目中导入JDBC),写入以下代码后,测试数据库连接是否成功

代码:

import java.sql.*;

public class MySQL_conn {

    public static void main(String args[]){

        Connection conn;

        String driver ="com.mysql.jdbc.Driver";

        String url ="jdbc:mysql://localhost:3306/数据库名";

        String user = "MySQL登录名";

        String password ="MySQL登录密码";

        try{

           Class.forName(driver);

            conn =DriverManager.getConnection(url,user,password);

            if(!conn.isClosed()){

               System.out.println("已连接上数据库!");

            }else{

               System.out.println("没有连接到数据库!");

            }

            //这是测试数据库中的表数据

            Statementstatement = conn.createStatement();

            String sql ="select * from 表名";

            ResultSet rs = statement.executeQuery(sql);

           System.out.println("-----------------");

            String name =null;

            String age = null;

            while(rs.next()){

                name = rs.getString("name");

                age =rs.getString("age");

                System.out.println(name +"\t" + age);

            }

            rs.close();

            conn.close();

       }catch(ClassNotFoundException e){

           System.out.println("Sorry,can`t find the Driver!");  

           e.printStackTrace();  

        }catch(SQLException e){

           e.printStackTrace();

        }finally{

           System.out.println("这是finally,不论结果如何,有没有错误,都会执行");

        }

    }

}


最后运行类文件,看是否连接成功。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值