首页 > 代码库 > jdbc连接数据库

jdbc连接数据库

 1 package com.howe2; 2 import java.sql.*; 3  4 public class test2 { 5     public static void main(String [] args) 6     { 7         PreparedStatement ps = null; 8         Connection con = null; 9         try10         {11             //1. 加载驱动12             Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");13             //2. 获得连接14             con = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName = howe", "sa", "sa");15             //3. 创建PreparedStatement16             ps = con.prepareStatement("insert into teacher values(?,?,?)");//一般用? 表示17             //给?赋值18             ps.setString(1, "t010");19             ps.setString(2, "wek");20             ps.setString(3, "Shanghai");21             //执行22             int i = ps.executeUpdate();23             if(i == 1)24             {25                 System.out.println("insert OK");26             }27             else28                 System.out.println("not OK");29         }catch(Exception e)30         {31             e.printStackTrace();32         }33         finally34         {35             try {36                 //关闭资源37                 if(ps != null)38                     ps.close();39                 if(con != null)40                     con.close();41             } catch (SQLException e) {42                 // TODO Auto-generated catch block43                 e.printStackTrace();44             }45         }46     }47 }

 

jdbc连接数据库