JDBC连接数据库 mysql

来源:互联网 发布:淘宝网眼镜批发市场 编辑:程序博客网 时间:2024/06/06 03:13

首先,下载符合mysql版本的mysql驱动。然后,将下载完的驱动jar包放在工程目录下(强调一下是工程包目录下)。

接着右键工程----->Properties----->Java Build Path 右边的Libraries----->Add JAR selection 选择驱动jar包。最后,点击OK。



链接代码如下:

import java.sql.Connection;import java.sql.DriverManager;import java.sql.SQLException;import java.sql.Statement;import java.util.Scanner;public class MainTest {public static void main(String[] args) {Connection cn = null;Statement stmt = null;try {Scanner sc = new Scanner(System.in);System.out.println("员工姓名");String empName = sc.next();System.out.println("员工性别");String empSex = sc.next();System.out.println("员工工资");float empSalary = sc.nextFloat();// 1.加载驱动Class.forName("com.mysql.jdbc.Driver");// 2.创建连接 这里的jdbctest是mysql中的数据库名,root为用户名,123为密码。cn = DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbctest", "root", "123");// 3.创建一个操作数据库对象stmt = cn.createStatement();// 4.发出sql语句stmt.executeUpdate("insert into employee(empName,empSalary,empSex) values('"+ empName + "'," + empSalary + ",'" + empSex + "')");// stmt.executeUpdate("update employee set empName='james' where empId=2;");// stmt.executeUpdate("delete from employee");} catch (ClassNotFoundException e) {e.printStackTrace();} catch (SQLException e) {e.printStackTrace();} finally {if (stmt != null) {try {stmt.close();} catch (SQLException e) {e.printStackTrace();}}if (cn != null) {try {cn.close();} catch (SQLException e) {e.printStackTrace();}}}}}



0 0