JDBC连接Mysql实例

创建数据库
指定数据库字符集和校对规则:
mysql> create database it315 default character set gb2312 collate gb2312_chinese_ci;
进入刚创建的数据库:
mysql> use it315;
Database changed
创建表:
mysql> create table student (id int primary key,name varchar(20),address varchar(20));
写一个属性文件: jdbc_mysql.properties,此文件存储一些连接相关的信息:
driver=com.mysql.jdbc.Driver                     // 驱动名称
url=jdbc:mysql://localhost:3306/it315    // 指定URL
user=root                                                         // 用户名
password=                                                       // 密码
characterEncoding=gb2312                        // 指定字符编码
写java源文件: JdbcConn.java
package vivi.servlet.jdbc;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Properties;

public class JdbcConn {
	
	//主文件
	public static void main(String[] args) {
		Connection conn = null;
		Statement stmt = null;
		ResultSet rs = null;

		Properties props = getProperties();
		if(props!=null){
			String driver = props.getProperty("driver");
			String url = props.getProperty("url");
			String user = props.getProperty("user");
			String password = props.getProperty("password");
			String characterEncoding = props.getProperty("characterEncoding");
			
			try{
				Class.forName(driver);			//加载驱动  
				conn = DriverManager.getConnection(url + "?characterEncoding="
                         + characterEncoding, user, password);		
				//conn = DriverManager.getConnection(url, user, password);		//建立连接 
				stmt = conn.createStatement();
				String sql = "insert into student values(1,'小伟','快维')";  
				stmt.executeUpdate(sql);		//执行sql语句  
				
				sql = "select * from Student";
				rs = stmt.executeQuery(sql);
				while (rs.next()) {				//从结果集中取出数据
                      System.out.print(rs.getInt(1) + "\t");
                      System.out.print(rs.getString(2) + "\t");
                      System.out.print(rs.getString(3) + "\n");
				} 
			}catch(Exception e){
				e.printStackTrace();
			}finally{
				try{
					if(rs != null){
						rs.close();
					}
					if(stmt != null){
						stmt.close();
					}
					if(conn != null){
						conn.close();
					}
				}catch(Exception e){
					e.printStackTrace();
				}
			}
		}
	}
	
	//读取数据连接属性文件
	public static Properties getProperties(){
		Properties props = new Properties();
		InputStream is = null;
		try{
			File file = new File("d:/jdbc.properties");
			is = new FileInputStream(file); 
			props.load(is);
		}catch(Exception ex){
			ex.printStackTrace();
			return null;
		}finally{
			if(is != null){
				try {
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return props;
	}
}
 

你可能感兴趣的:(java,sql,mysql,jdbc,servlet)