JDBC
Java连接MySQL数据库
下载Connector/J地址:http://www.mysql.com/downloads/connector/j/
解压后就可以看到数据库的包
通过右键build path进入Java build path界面
将刚下载的压缩包添加进去
建立一个Java工程
建立一个数据库连接类DBHelper类
package com.xuexi.db; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; /** * 获取数据库连接类 * @author sker * */ public class DBHelper { /** * 数据库地址 */ private static final String URL = "jdbc:mysql://127.0.0.1/clock"; /** * mysql 驱动 */ private static final String DRIVER = "com.mysql.jdbc.Driver"; /** * 用户名 */ private static final String USER = "root"; /** * 密码 */ private static final String PASSWORD = "123456"; /** * 连接数据库 * @param sql * @throws ClassNotFoundException */ public static Connection getConnection() throws ClassNotFoundException{ Connection conn = null; try { Class.forName(DRIVER);//指定连接类型 conn = DriverManager.getConnection(URL, USER, PASSWORD); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); }//获取连接 return conn; } /** * 关闭数据库连接 */ public static void close(Connection conn) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } }
然后建立一个用来定义操作sql语句的方法的类Dao类
package com.xuexi.dao; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import com.xuexi.db.DBHelper; /** * dao层 * @author sker * */ public class Dao { /** * 执行sql语句 * @param sql * @throws ClassNotFoundException * @throws SQLException */ public static void DoSql(String sql) throws ClassNotFoundException{ //每次都要进行数据库的连接和关闭,除非建立连接池 Connection conn = DBHelper.getConnection(); Statement st; try { if(null != conn){ st = conn.createStatement(); st.execute(sql); st.close(); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } DBHelper.close(conn); } /** * 查询sql语句 * @param sql * @throws ClassNotFoundException * @throws SQLException */ public static void query(String sql) throws ClassNotFoundException{ Connection conn = DBHelper.getConnection(); Statement st; try { if(null != conn){
//注意createStatement和prepareStatement的区别,一般使用prepareStatement,
//因为prepareStatement会做一次sql过滤,如:sql=“select * from user where id=1 or 1=1” st = conn.createStatement(); ResultSet result = st.executeQuery(sql);
//查询的不止一条记录 while(result.next()){ String loginName = result.getString("loginname"); String name = result.getString("name"); System.out.println(loginName + name); } st.close(); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } DBHelper.close(conn); } }
然后通过定义main或者是junit来执行语句
import static org.junit.Assert.*; import org.junit.Test; import com.xuexi.dao.Dao; public class JDBCTest { @Test public void insertUserInfo() throws ClassNotFoundException { StringBuffer sb = new StringBuffer(); sb.append("insert into user(loginname,PASSWORD,name,birthday,male,registertime,phone)") .append("values('18389351725','123456','小红','1996-2-23','1','2016-2-15','18389351725')"); Dao.DoSql(sb.toString()); } }
执行后查看数据库user表