1.首先在电脑上安装mysql
2.然后在开发项目中导入相应的jar包
3.然后在代码中调用相应类进行调用。
例子:
事先在mysql中创建了名为jdbc的数据库
建立了叫user的表:
mysql> create database jdbc;
Query OK, 1 row affected (0.05 sec)
mysql> use jdbc
Database changed
mysql> create table users(
-> id int primary key auto_increment,
-> name varchar(40),
-> password varchar(40),
-> email varchar(60),
-> birthday date)character set utf8 collate utf8_general_ci;
Query OK, 0 rows affected, 1 warning (0.11 sec)
mysql> insert into users(name,password,email,birthday)
-> values('zs','123456','[email protected]','1980-12-03');
Query OK, 1 row affected (0.09 sec)
mysql> select * from users;
+----+------+----------+-------------+------------+
| id | name | password | email | birthday |
+----+------+----------+-------------+------------+
| 1 | zs | 123456 | zs@sina.com | 1980-12-03 |
+----+------+----------+-------------+------------+
然后eclipse中web连接mysql:
首先,将jar包复制到WebContent中,然后右键包选择build path然后add to build path.
然后写入下列代码:
package cn.itcast.jdbc.example;
import java.sql.*;
public class Example01 {
public static void main(String[] args) throws SQLException{
Statement stmt=null;
ResultSet rs=null;
Connection conn=null;
try{
Class.forName("com.mysql.cj.jdbc.Driver");
String url="jdbc:mysql://localhost:3306/jdbc?&useSSL=false&serverTimezone=UTC";
String username="root";
String password="root";
conn = DriverManager.getConnection(url,username,password);
stmt= conn.createStatement();
String sql = "select * from users";
rs = stmt.executeQuery(sql);
System.out.println("id|name|password|email|birthday");
while(rs.next())
{
int id = rs.getInt("id");
String name = rs.getString("name");
String psw = rs.getString("password");
String email = rs.getString("email");
Date birthday = rs.getDate("birthday");
System.out.println(id +" | "+name+" | "+psw+" | "+email+" | "+birthday);
}
}catch(ClassNotFoundException e)
{
e.printStackTrace();
}
finally{
if(rs!=null){
try{
rs.close();
}catch(SQLException e){
e.printStackTrace();
}
rs=null;
}
if(stmt!=null){
try{
stmt.close();
}
catch(SQLException e)
{
e.printStackTrace();
}stmt=null;
}if(conn!=null){try{
conn.close();
}catch(SQLException e)
{
e.printStackTrace();
}
conn=null;
}
}
}
}
运行之,成功访问。