JDBC连接MySQL

2013-01-05  付民 

加载及注册JDBC驱动程序

Class.forName(“com.mysql.jdbc.Driver”);

Class.forName(“com.mysql.jdbc.Driver”).newInstance();

 

JDBC URL 定义驱动程序与数据源之间的连接

标准语法:

<protocol(主要通讯协议)>:<subprotocol(次要通讯协议,即驱动程序名称)>:<data source identifier(数据源)>

MySQL的JDBC URL格式:

jdbc:mysql//[hostname][:port]/[dbname][?param1=value1][&param2=value2]….

示例:jdbc:mysql://localhost:3306/sample_db?user=root&password=your_password

 常见参数:

user                       用户名

password                  密码

autoReconnect                  联机失败,是否重新联机(true/false)

maxReconnect              尝试重新联机次数

initialTimeout               尝试重新联机间隔

maxRows                   传回最大行数

useUnicode                 是否使用Unicode字体编码(true/false)

characterEncoding          何种编码(GB2312/UTF-8/…)

relaxAutocommit            是否自动提交(true/false)

capitalizeTypeNames        数据定义的名称以大写表示

建立连接对象

String url=”jdbc:mysql://localhost:3306/sample_db?user=root&password=your_password”;

Connection con = DriverManager.getConnection(url);

建立SQL陈述式对象(Statement Object)

Statement stmt = con.createStatement();

执行SQL语句

executeQuery()

String query = “select * from test”;

ResultSet rs=stmt.executeQuery(query);

结果集ResultSet

while(rs.next())

{rs.getString(1);rs.getInt(2);}

executeUpdate()

String upd=”insert into test (id,name) values(1001,xuzhaori)”;

int con=stmt.executeUpdate(upd);

execute()

 

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

mysql>create database studentinfo;

 

然后编写java代码,ConnectToMySQL.java

import java.sql.*;

public class ConnectToMySQL {
public static Connection getConnection() throws SQLException ,
java.lang.ClassNotFoundException{
String url = “jdbc:mysql://localhost:3306/studentinfo”;
Class.forName(“com.mysql.jdbc.Driver”);
String userName = “root”;
String password = “”;
Connection con = DriverManager.getConnection(url,userName,password);
return con;
}

 
public static void main(String[] args) {
try{
Connection con = getConnection();
Statement sql = con.createStatement();
sql.execute(“drop table if exists student”);
sql.execute(“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));”);
sql.execute(“insert student values(1,’AAA’,’99′)”);
sql.execute(“insert student values(2,’BBB’,’77′)”);
sql.execute(“insert student values(3,’CCC’,’65′)”);
String query = “select * from student”;
ResultSet result = sql.executeQuery(query);
System.out.println(“Student表数据如下:”);
System.out.println(“———————————”);
System.out.println(“学号”+” ”+”姓名”+” ”+”数学成绩”);
System.out.println(“———————————”);
int number;
String name;
String math;
while(result.next()){
number = result.getInt(“id”);
name = result.getString(“name”);
math = result.getString(“math”);
System.out.println(number + “ ” + name + “ ” + math);
}
sql.close();
con.close();

}catch(java.lang.ClassNotFoundException e){
System.err.println(“ClassNotFoundException:” + e.getMessage());
}catch(SQLException ex){
System.err.println(“SQLException:” + ex.getMessage());
}
}
}

 

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

 

 

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

import java.sql.ResultSet;

import java.sql.Statement;

import java.sql.*;

 

public class BaseConnection {
private Connection con = null;

protected Connection getCon(){

ResultSet rs=null;

Statement stmt = null;
try {

Class.forName(“org.gjt.mm.mysql.Driver”);
String url=”jdbc:mysql://192.168.0.10/数据库名?user=USR&password=PWD”;
conn = DriverManager.getConnection(url);

stmt = conn.createStatement();

} catch (ClassNotFoundException e) {

e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return con;
}

}

欢迎转载,请注明转自:测试之路-My Test Space
本文链接: JDBC连接MySQL

376°/3766 人阅读/0 条评论 发表评论

登录 后发表评论