现在的位置: 首页 > 综合 > 正文

Java连接mysql数据库

2018年03月23日 ⁄ 综合 ⁄ 共 1356字 ⁄ 字号 评论关闭

首先,打开MySQL Query Browser,在当前Test数据库下,新建一个student表,有如下属性:

create table student (name varchar(10),id int(2),sex varchar(10));

 

程序见下:

package com.JDBC;

import java.sql.*;

public class JDBCTest {

public static void main(String[] args) {String driver = "com.mysql.jdbc.Driver"; // 驱动程序名

String url = "jdbc:mysql://localhost/test"; // URL指向要访问的数据库名scutcs

String user = "root"; // MySQL配置时的用户名

String password = "123456"; // MySQL配置时的密码

try {

Class.forName(driver); // 加载驱动程序

Connection conn = DriverManager.getConnection(url, user, password); // 连续数据库

if (!conn.isClosed())
System.out.println("Succeeded connecting to the Database!"); // 验证是否连接成功

Statement statement = conn.createStatement(); // statement用来执行SQL语句

String sql = "select * from student"; // 要执行的SQL语句

ResultSet rs = statement.executeQuery(sql); // 结果集

System.out.println("-----------------------------------------");
System.out.println("执行结果如下所示:");
System.out.println("-----------------------------------------");
System.out.println(" 学号" + "/t/t" + " 姓名" + "/t/t" + "性别");
System.out.println("-----------------------------------------");

String name = null;

while (rs.next()) {

name = rs.getString("name"); // 选择no这列数据

System.out.println(rs.getString("id") + "/t/t" + name + "/t/t"
 + rs.getString("sex")); // 输出结果
}

rs.close();
conn.close();

} catch (ClassNotFoundException e) {

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

} catch (SQLException e) {

e.printStackTrace();

} catch (Exception e) {

e.printStackTrace();

}
}
}

抱歉!评论已关闭.