JAVA连接MySQL数据库
首先需要安装MySQL(安装流程),创建一个数据库,下面代码中使用的是mysql中一个名为“wpt”的数据库,数据库的账号密码都为“root”。
代码如下:
import java.sql.*;
public class ConnectMysql {
public static void main(String[] args) throws SQLException {
Connection connect = null;
try {
Class.forName("com.mysql.jdbc.Driver");//加载驱动
} catch(Exception e) {
System.out.println("加载驱动失败");
}
try {
/*连接URL为"jdbc:mysql://服务器地址"+"mysql用户名"+"密码"*/
connect = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/wpt","root","root");
} catch (Exception e) {
System.out.println("连接mysql失败");
}
Statement stmt = connect.createStatement();//建立执行sql语句的工具接口
String sql = "select mname from member;";//查询member表中所有人的名字
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()) {
System.out.println(rs.getString("mname"));
}
}
}
创建member表以及插入数据的命令:
create table member(
mno char(15) not null,
mname varchar(15) unique,
sex char(5) not null check(sex='男' or sex='女'),
birthday date not null,
age int not null,
dept varchar(10) not null,
post varchar(15) not null,
start_date date not null
);
insert
into member
values('0001','李勇','男',('1985-01-02'),'33','研发部','研发部长',('2012-05-11'));
insert
into member
values('0002','刘晨','男',('1987-01-02'),'31','研发部','项目策划',('2012-06-01'));
insert
into member
values('0003','王敏','女',('1985-11-02'),'33','财务部','财务会计',('2011-06-11'));
insert
into member
values('0004','张立','男',('1990-01-02'),'20','人事部','人事部长',('2011-05-11'));
insert
into member
values('0005','李二','男',('1995-01-02'),'23','研发部','普通员工',('2017-05-11'));
insert
into member
values('0006','张三','男',('1982-01-02'),'36','财务部','财务部长',('2010-05-11'));
insert
into member
values('0007','李晨','男',('1994-01-02'),'24','人事部','普通员工',('2017-08-23'));
insert
into member
values('0008','王珊','女',('1985-01-02'),'33','营销部','营销部长',('2011-11-11'));
insert
into member
values('0009','王茂','男',('1986-01-02'),'32','财务部','普通员工',('2012-05-11'));
insert
into member
values('0010','柳风','男',('1995-11-02'),'23','研发部','普通员工',('2017-05-11'));
insert
into member
values('0011','赵倩','女',('1995-01-12'),'23','研发部','普通员工',('2017-05-11'));
执行结果为:
如果程序不能正常运行出现以下错误:
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:582)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:190)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:499)
at java.base/java.lang.Class.forName0(Native Method)
at java.base/java.lang.Class.forName(Class.java:291)
at com.wpt.Test009.main(Test009.java:7)
java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/wptget data error!
at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:702)
at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:228)
at com.wpt.Test009.main(Test009.java:17)
这是因为eclipse缺少一个文件,解决方法参照我的另一篇博客。