mysql连接问题
import java.sql.*;
public class DataBaseTest {
public static Connection getConnection() throws
SQLException,
java.lang.ClassNotFoundException {
//取得连接的url
String url = "jdbc:mysql://localhost:3306/studentinfo ";
//加载MySQL的jdbc驱动
Class.forName( "org.gjt.mm.mysql.Driver ");
//使用能访问MySQL数据库的用户名root
String userName = "root ";
//使用口令
String password = "000000 ";
//打开数据库连接
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 student ");
//执行了一个sql语句生成了一个名为student的表
sql
.executeUpdate( "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.executeUpdate( "insert student values(1, 'liyinglin ',98) ");
sql.executeUpdate( "insert student values(2, 'jiangshan ',79) ");
sql.executeUpdate( "insert student values(3, 'wangjiawu ',100) ");
sql.executeUpdate( "insert student values(4, 'xingweiqi ',89) ");
sql.executeUpdate( "insert student values(5, 'lingsheng ',61) ");
//执行查询数据库的sql语句
String query = "select * from student ";
//返回一个结果集
ResultSet result = sql.executeQuery(query);
System.out.println( "Student表中的数据如下: ");
//使用了一个while循环打印出了student表中的所有的数据
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( "Class
NotFoundException: ");
//加载jdbc错误,所要用的驱动没找到
System.err.println(e.getMessage());
//其他错误
} catch (SQLException ex) {
System.err.println( "SQLException: " + ex.getMessage());
//显示数据库连接错误或者查询错误
}
}
}