2024年3月13日发(作者:)

JDBC连接MySQL经典方案

最近在学习数据库开发的一些实例,这里浅谈一下用JDBC连接数据库MySQL(当

然也可以连接SQL Sever或Oracle了,只是我更喜欢开源软件,同时也更简单)。

首先正确安装好MySQL,建立好数据库studentinfo

mysql>create database studentinfo;

然后编写java代码,

import .*;

public class ConnectToMySQL {

public static Connection getConnection() throws SQLException ,

otFoundException{

String url = "jdbc:mysql://localhost:3306/studentinfo";

e("");

String userName = "root";

String password = "";

Connection con = nection(url,userName,password);

return con;

}

public static void main(String[] args) {

try{

Connection con = getConnection();

Statement sql = Statement();

e("drop table if exists student");

e("create table student(id int not null auto_increment,name

varchar(20) not null default 'name',math int not null default 60,primary

key(id));");

e("insert student values(1,'AAA','99')");

e("insert student values(2,'BBB','77')");

e("insert student values(3,'CCC','65')");

String query = "select * from student";

ResultSet result = eQuery(query);

n("Student表数据如下:");

n("---------------------------------");

n("学号"+" "+"姓名"+" "+"数学成绩");

n("---------------------------------");

int number;

String name;

String math;

while(()){

number = ("id");

name = ing("name");

math = ing("math");

n(number + " " + name + " " + math);

}

();

();

}catch(otFoundException e){

n("ClassNotFoundException:" + sage());

}catch(SQLException ex){

n("SQLException:" + sage());

}

}

}

要注意的是使用MySQL数据库,需要用到对应的JDBC驱动程序

mysql-connector-java-5.0.3

import tion;

import Manager;

import eption;

import Set;

import ent;

import .*;

public class BaseConnection {

private Connection con = null;

protected Connection getCon(){

ResultSet rs=null;

Statement stmt = null;

try {

e("");

String url="jdbc:mysql://192.168.0.10/数据库名?user=USR&password=PWD";

conn = nection(url);

stmt = Statement();

} catch (ClassNotFoundException e) {