MyEclipse与Mysql数据库的连接
Posted Brenda
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了MyEclipse与Mysql数据库的连接相关的知识,希望对你有一定的参考价值。
1.载入mysql驱动程序
Class.forName("com.mysql.jdbc.Driver"); // 载入MySql驱动程序
2.建立Connection连接对象
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/my_db?user=root&password=root");
当中
url = "jdbc:mysql://localhost/";
serverName = "localhost";
portNumber = "3306";
databaseName = "my_db";
userName = "root";
password = "root";
3.建立Statement语句对象
Statement st = con.createment();
4.运行sql语句
st.executeUpdate(“SQL语句”);//插入
st.executeUpdate(“SQL语句”);//更新
st.executeexecuteQuery(“SQL语句”);//查询
5.关闭连接
con.close();
6.实现案例
DBConn.java中是对连接数据库的实现
package db; import java.sql.Connection; import java.sql.DriverManager; public class DBConn { /* 获取Conncetion对象并返回 */ public Connection getConnection() { Connection con=null; try { Class.forName("com.mysql.jdbc.Driver"); // 载入MySql驱动程序 //con = DriverManager.getConnection("jdbc:mysql://localhost/cloud_db?user=root&password=root&autoReconnect=true&useUnicode=true&characterEncoding=utf8"); con=DriverManager.getConnection("jdbc:mysql://localhost:3306/my_db?user=root&password=root&useUnicode=true&characterEncoding=GBK"); //jdbc:mysql://localhost/数据库名称?useUnicode=true&characterEncoding=GBK } catch (Exception e) { System.out.println("数据库获取失败!
"); e.printStackTrace(); } return con; } }
StudentImpl.java是对数据库数据的录入
package impl; import pojo.Student; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import db.DBConn; public class StudentImpl { public String joinString(String[] slikes) { String joinlikes = ""; for (String temp : slikes) { joinlikes += temp + "-"; } return joinlikes.substring(0, joinlikes.length() - 1); } public void saveStudent(Student student){ //连接数据库完毕数据的录入操作 Connection con = null; PreparedStatement pre = null; DBConn conns = new DBConn(); con = conns.getConnection(); try{ pre = con.prepareStatement("insert into student (sname,spass,Slikes) values(?,?,?)"); pre.setString(1,student.getSname()); pre.setString(2,student.getSpass()); pre.setString(3,student.getSlikes()); boolean b = pre.execute(); }catch(SQLException e){ e.printStackTrace(); }finally{ try { con.close(); } catch (SQLException e) { e.printStackTrace(); } } } }
以上是关于MyEclipse与Mysql数据库的连接的主要内容,如果未能解决你的问题,请参考以下文章