--------------------------------------------------------------------------------------------------
String url =
"jdbc:mysql://localhost:3306/image";
String user = "root";
String password = "java";
String driver = "org.gjt.mm.mysql.Driver";
public List getList()
{
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
} catch (Exception E) {
System.out.print("无法加载驱动:" + driver);
}
try {
Connection con = (Connection)DriverManager.getConnection(url, user,
password);
if (!con.isClosed()) {
System.out.println("打开数据库成功");
}
Statement smt = (Statement) con.createStatement();
smt.executeUpdate("select * from image");
smt.close();
con.close();
} catch (SQLException SE) {
System.out.print("打开数据库失败");
}
return null;
}
--------------------------------------------------------------------------------------------------
import java.sql.*;
public class DataBaseTest {
public static Connection getConnection() throws SQLException,
java.lang.ClassNotFoundException {
//取得连接的url
String url = "jdbc:mysql://localhost:3306/top";
//加载MySQL的jdbc驱动
Class.forName("com.mysql.jdbc.Driver");
//使用能访问MySQL数据库的用户名root
String userName = "root";
//使用口令
String password = "1";
//打开数据库连接
Connection con = DriverManager.getConnection(url, userName,
password);
return con;
}
public static void main(String args[]) {
try {
//取得数据库的连接
Connection con =
getConnection();
//创建一个声明,用来执行sql语句
Statement sql =
con.createStatement();
//如果同名数据库存在,删除掉
//sql.executeUpdate("drop
table if exists book");
//执行了一个sql语句生成了一个名为book的表
//sql
// .executeUpdate("create
table book (id int not null auto_increment,name varchar(20) not
null default 'name',math int not null default 60,primary key (id));
");
//向表中插入数据
//sql.executeUpdate("insert
book values(1,'liyinglin',98)");
//sql.executeUpdate("insert
book values(2,'jiangshan',79)");
//sql.executeUpdate("insert
book values(3,'wangjiawu',100)");
//sql.executeUpdate("insert
book values(4,'xingweiqi',89)");
//sql.executeUpdate("insert
book values(5,'lingsheng',61)");
//执行查询数据库的sql语句
String query = "select * from
book";
//返回一个结果集
ResultSet result =
sql.executeQuery(query);
System.out.println("Book表中的数据如下:");
//使用了一个while循环打印出了book表中的所有的数据
System.out.println("----------------------------------");
System.out.println("学号 " +
" " + "姓名" +
" " + "数学成绩");
System.out.println("----------------------------------");
while (result.next()) {
int number =
result.getInt("id");
String name
= result.getString("name");
String
mathScore = result.getString("math");
//取得数据库中的数据
System.out.println(" " + number +
" " + name +
" "
+ mathScore);
}
//关闭声明和连接
sql.close();
con.close();
} catch (java.lang.ClassNotFoundException e) {
System.err.print("ClassNotFoundException: ");
//加载jdbc错误,所要用的驱动没找到
System.err.println(e.getMessage());
//其他错误
} catch (SQLException ex) {
System.err.println("SQLException: " + ex.getMessage());
//显示数据库连接错误或者查询错误
}
}