码迷,mamicode.com
首页 > 数据库 > 详细

MyEclipse与Mysql数据库的连接

时间:2016-03-26 20:09:59      阅读:185      评论:0      收藏:0      [点我收藏+]

标签:

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数据库的连接

标签:

原文地址:http://www.cnblogs.com/mengfanrong/p/5323825.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!