您的位置:首页 > 数据库 > MySQL

JDBC连接数据库 mysql

2014-01-12 20:21 281 查看
首先,下载符合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();
}
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: