开始使用JDBC
使用JDBC连接mysql数据库,需要先下载一个mysql驱动器。
例子程序如下:
[java]
package com.you.domain;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class Domain {
private static String url = "jdbc:mysql://localhost:3306/test?charset=utf8";
private static String username = "root";
private static String password = "mysql";
static {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
throw new ExceptionInInitializerError(e);
}
}
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(url,username,password);
}
//向数据库中插入数据
public void insert(String name, String word, String 易做图, String birth, String email, String address) {
Connection con = null;
PreparedStatement pt = null;
try {
con = getConnection();
String sql = "insert into register(name,word,易做图,birth,email,address) value(?,?,?,?,?,?)";
pt = con.prepareStatement(sql);
pt.setString(1, name);
pt.setString(2, word);
pt.setString(3, 易做图);
pt.setString(4, birth);
pt.setString(5, email);
pt.setString(6, address);
pt.executeUpdate();
} catch (SQLException e) {
throw new RuntimeException();
}finally{
if(pt != null) {
try {
pt.close();
} catch (SQLException e) {
throw new RuntimeException();
}
}
if(con != null) {
try {
con.close();
} catch (SQLException e) {
throw new RuntimeException();
}
}
}
}
//查询数据 www.zzzyk.com
public List<String> queryDB(String name) {
Connection cn = null;
PreparedStatement ps = null;
ResultSet rs = null;
List<String> list = new ArrayList<String>();
try {
cn = getConnection();
String sql = "select word from register where name = ?";
ps = cn.prepareStatement(sql);
ps.setString(1, name);
rs = ps.executeQuery();
while(rs.next()) {
list.add(rs.getString("word"));
}
} catch (SQLException e) {
throw new RuntimeException();
}finally {
if(rs != null) {
try {
rs.close();
} catch (SQLException e) {
throw new RuntimeException();
}
}
if(ps != null) {
&nbs
补充:软件开发 , Java ,