标签:style blog http color java os io 数据
Java数据库连接(JDBC)由一组用 Java 编程语言编写的类和接口组成。JDBC 为工具/数据库开发人员提供了一个标准的 API,使他们能够用纯Java API 来编写数据库应用程序。然而各个开发商的接口并不完全相同,所以开发环境的变化会带来一定的配置变化。本文介绍的是连接SQLServer数据库:
1.打开SQLServer的配置管理器:
2.打开TCP/IP的属性,IPALL的端口改为1433
3.打开服务,重新启动SQL Server(SQLEXPRESS)
4.下面开始写简易的JDBC:
String DRIVER = "com.microsoft.sqlserver.jdbc.SQLServerDriver"; String URL = "jdbc:sqlserver://localhost:1433;DatabaseName=bookDB"; String USERNAME = "sa"; String PASSWORD = "1234";
1 package com.ccec.jdbc; 2 3 import java.beans.Statement; 4 import java.sql.Connection; 5 import java.sql.DriverManager; 6 import java.sql.PreparedStatement; 7 import java.sql.ResultSet; 8 import java.sql.SQLException; 9 10 public class jdbc { 11 private static final String DRIVER = "com.microsoft.sqlserver.jdbc.SQLServerDriver"; 12 private static final String URL = "jdbc:sqlserver://localhost:1433;DatabaseName=bookDB"; 13 private static final String USERNAME = "sa"; 14 private static final String PASSWORD = "1234"; 15 16 public boolean login(String username, String password) { 17 Connection con = null; 18 PreparedStatement st = null; 19 ResultSet rs = null; 20 21 try { 22 Class.forName(DRIVER); 23 con = DriverManager.getConnection(URL, USERNAME, PASSWORD); 24 String sql = "select userName,pwd from userInfo where userName=? and pwd=?"; 25 st = con.prepareStatement(sql); 26 st.setString(1, username); 27 st.setString(2, password); 28 rs = st.executeQuery(); 29 30 if (rs.next()) { 31 System.out.println(username); 32 return true; 33 } 34 } catch (ClassNotFoundException e) { 35 // TODO Auto-generated catch block 36 e.printStackTrace(); 37 } catch (SQLException e) { 38 // TODO Auto-generated catch block 39 e.printStackTrace(); 40 } finally { 41 try { 42 if (rs != null) { 43 rs.close(); 44 } 45 if (st != null) { 46 st.close(); 47 } 48 if (con != null) { 49 con.close(); 50 } 51 } catch (SQLException e) { 52 // TODO Auto-generated catch block 53 e.printStackTrace(); 54 } 55 } 56 return false; 57 } 58 }
标签:style blog http color java os io 数据
原文地址:http://www.cnblogs.com/stayreal/p/3909391.html