JDBC访问数据库

package jspex.jdbc;

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

public class JDBCDemo {
	/***
	 * SQL
	Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver").newInstance(); 
	String url="jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=数据库实例名"; 
	*/
	/***
	 * mysql
	Class.forName("com.mysql.jdbc.Driver"); 
	String url="jdbc:mysql://localhost:3306/数据库实例名"; 
	*/
	private static final String URL="jdbc:oracle:thin:@localhost:1521:ORCL";
	private static final String USERNAME="scott";
	private static final String PWD="tiger";
	
	public static void update(){ //增删改
		Connection connection = null;
		Statement stmt = null;
		try{
			//a.导入驱动,加载具体的驱动类
			Class.forName("oracle.jdbc.OracleDriver");  //加载具体的驱动类
			//b.与数据库建立连接
			connection=DriverManager.getConnection(URL, USERNAME, PWD);
			//c.发送sql,执行(增删改查)
			stmt =connection.createStatement();
			String sql="insert into student values(1,'zs',23,'s1')";
			//执行SQL
			int cnt=stmt.executeUpdate(sql);  //返回值表示增删改几条数据
			//d.处理结果
			if(cnt>0){
				System.out.println("操作成功!");
			}
		}catch(ClassNotFoundException e){
			e.printStackTrace();
		}catch(SQLException e){
			e.printStackTrace();
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			try {
				if(stmt!=null) stmt.close();
				if(connection!=null) connection.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			
		}
	}
	
	public static void main(String[] args) {
			update();

	}

}

 

你可能感兴趣的:(javaweb)