已经安装了mysql和navicat
一、先到mysql官网下载驱动文件,
选择no thanks 后下载。
二、打开eclipse创建Dynamic Wed Project项目
记住创建项目时请勿添加服务器
右击项目找到Build path─configure build path─
将下载好的驱动文件添加。
三、新建一个class类写上一下代码。
import java.sql.*;
public class Demo {
public static void main(String args[]) {
try {
Class.forName("com.mysql.jdbc.Driver"); //加载MYSQL JDBC驱动程序
//Class.forName("org.gjt.mm.mysql.Driver");
System.out.println("Success loading Mysql Driver!");
}
catch (Exception e) {
System.out.print("Error loading Mysql Driver!");
e.printStackTrace();
}
try {
Connection connect = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/??","root","java");//java这个空填写的是你自己设的密码
//连接url为 jdbc:mysql//服务器地址/数据库名
System.out.println("Success connect Mysql server!");
Statement stmt = connect.createStatement();
ResultSet rs = stmt.executeQuery("select * from user");
//user 为你表的名称,可以在MySQL命令行用show tables;显示
while (rs.next()) {
System.out.println(rs.getString("name"));//设计的表必需有“name”否则报错
}
}
catch (Exception e) {
System.out.print("get data error!");
e.printStackTrace();
}
}
}
四、在数据库中的操作。
新建表其中必须包含name名(否则运行时会报错)
在表中随意填上信息。