jdbc连接mysql数据库

jdbc连接数据库都是几个步骤:

1)加载驱动
2)建立连接
3)创建查询语句
4)返回结果集

如果想要设置事务,则需在操作之前设置默认提交方式即可,关于事务,此处不再赘述。

代码如下:


package com.test.lihongxu;

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


	public class MysqlConnect {
		
		 public  static Connection getConnetion(){
	            Connection con= null;
	             try {
                  Class. forName("com.mysql.jdbc.Driver");
                  //建立连接很简单,加载完驱动后,传递三个参数,1)url 2)用户名,3)密码 即可
                  con = DriverManager.getConnection("jdbc:mysql://localhost/minisite?useUnicode=true&characterEncoding=GBK", "root" , "admin" );
	             } catch (SQLException e) {
	                   e.printStackTrace();
	             } catch (ClassNotFoundException e) {
					e.printStackTrace();
				 }
	             return con;
	      }
		 
		/**
		 * 测试
		 * @param args
		 */
	    public static void main(String[] args) {
	    	  Connection con=getConnetion();
		        try {
		        	//设置事务,默认提交方式为true,改为false即可
		            con.setAutoCommit( false);
		            Statement stm=con.createStatement();
		            ResultSet set=stm.executeQuery( "select * from table");
		            //假设 table里面有三个字段,取出打印
		             while(set.next()){
		                  System.out.println(set.getInt(1));
		                  System.out.println(set.getString(2));
		                  System.out.println(set.getString(3));
		            }
		            //提交事务
		            con.commit();
		            con.close();
		      } catch (SQLException e) {
		             try {
		                  con.rollback();//回滚事务
		                  System. out.println("not Ok" );
		            } catch (SQLException e1) {
		                  e1.printStackTrace();
		            }     
		            e.printStackTrace();
		      
		      }
		}
	      
	}

猜你喜欢

转载自lhkzyz.iteye.com/blog/1669223