`
x125521853
  • 浏览: 71433 次
  • 性别: Icon_minigender_1
  • 来自: 武汉
社区版块
存档分类
最新评论

JDBC-MySQL连接数据库

阅读更多

//MySQL连接数据库

package database;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class JdbcMySql {
	public static void main(String[] args) {
		Connection conn = null;
		Statement st = null;
		ResultSet rs = null;
		
		try {
			//加载驱动 MySql
			Class.forName("com.mysql.jdbc.Driver");
			//创建连接
			conn = DriverManager.getConnection( "jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8",   
                    "root", "admin");
			//获取指令对象 
			st = conn.createStatement();
			//发送指令,并返回结果  
			rs = st.executeQuery("select * from student");
			//获取结果集
			while(rs.next()){
				System.out.println("id:"+rs.getInt(1));
				System.out.println("username:"+rs.getString(2));
			}
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			try{
				if (rs != null) {   
                    rs.close();   
                }   
                if (st != null) {   
                    st.close();   
                }   
                if (conn != null) {   
                    conn.close();   
                }   
			}catch(SQLException e){
				e.printStackTrace();
			}
		}
	}
}

 

   //数据  

create table student(
    id int auto_increment primary key,
    username varchar(10)
)engine=innodb default charset=utf8
insert into student(username) values('李四');
insert into student(username) values('张三');
insert into student(username) values('王五');
insert into student(username) values('赵六');
insert into student(username) values('林奇');

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics