标签:
1.下载驱动。
2.eclipse->add extend jars -> 添加驱动。
3.测试:
在mysql 建立数据库和表,在eclipse 里对数据库进行操作。
代码:
mysql:
create database test; create table user (name, varchar(20), password varchar(20)); insert into user values (‘xiaotao‘, ‘123456‘);
Java (查看和添加记录):
package sql; import java.lang.reflect.Executable; import java.sql.*; public class Connector { public static void main(String[] args) { try { Class.forName("com.mysql.jdbc.Driver"); System.out.println("Success loading Mysql Driver"); }catch (Exception e) { System.out.println("Error loading Mysql Driver!"); e.printStackTrace(); } try { Connection connect = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "123456"); System.out.println("Success connect Mysql server!"); Statement stmt = connect.createStatement(); ResultSet rs = stmt.executeQuery("select *from user"); while(rs.next()) { System.out.println(rs.getString("name")); } PreparedStatement stmt2 = connect.prepareStatement("insert into user value(?, ?)"); stmt2.setString(1, "sunhongtao"); stmt2.setString(2, "123"); stmt2.executeUpdate(); } catch (Exception e) { System.out.println("get data error!"); e.printStackTrace(); } } }
标签:
原文地址:http://www.cnblogs.com/icode-girl/p/5557595.html