Java数据库连接

简单的数据库连接示例:

package com.test1; /** * 演示使用jdbc-odbc桥连方式连接数据库 * 1.配置数据源 * 2.程序中去连接数据源 * 3.程序中关闭数据源 */ import java.sql.*; public class Test1 { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Connection ct=null; Statement sm=null; try{ //1.加载驱动(作用是把需要的驱动程序加入内存) Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); //2.得到连接,指定连结到那个数据源,用户名,和密码 ct = DriverManager.getConnection("jdbc:odbc:mytest","gkp","123"); //3.创建Statement或者是PreparedStatement[区别] //Statement用处是:主要是用于发送sql语句,到数据库 sm= ct.createStatement(); //4.执行(crud,创建数据库,备份数据库,删除数据...) //1.演示添加一条数据到表中 //executeUpdate可以执行cud操作(添加,删除,修改) int i = sm.executeUpdate("insert into Emp values('1','软件工程')"); if(i == 1){ System.out.println("添加OK"); }else{ System.out.println("添加失败"); } }catch(Exception e){ e.printStackTrace(); }finally{ try { //关闭资源 if(sm!=null){ sm.close(); } if(ct!=null){ ct.close(); } } catch (Exception e2) { // TODO: handle exception } } } }

你可能感兴趣的:(java,数据库,exception,jdbc,null,insert)