首页 > 代码库 > Eclipse连接Mysql数据库
Eclipse连接Mysql数据库
1、安装mysql数据库(具体方法不赘述了);登陆mysql语句:mysql -h localhost -u root -p 1905;
2、下载jdbc;
3、开启eclipse之后,选择工程,将jdbc的jar包导入;
4、写一个程序验证下:
package webJDBC;
import java.sql.*;
public class MysqlJdbc {
public static void main(String[] args){
//加载jdbcDriver
try {
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Success loading Mysql Driver!");
} catch (Exception e) {
System.out.println("Error!");
e.printStackTrace();
}
try{
//链接数据库
Connection connect = DriverManager.getConnection("jdbc:mysql://localhost:3306/SY","root","1905");
System.out.println("success connect Mysql Server!");
Statement stmt = connect.createStatement();
//插入2条数据
int num =2;
PreparedStatement statement = connect.prepareStatement("insert into user values(?,?)");
for(int i=0;i<num;i++){
statement.setString(1, "zhaopeng"+i);
statement.setString(2, "mima"+i);
statement.executeUpdate();
}
ResultSet rs = stmt.executeQuery("select * from user");
while(rs.next()){
System.out.println(rs.getString("name"));
}
}catch(Exception e){
System.out.println("get data error!");
e.printStackTrace();
}
}
}
Eclipse连接Mysql数据库