[color=red][size=large]连接mysql[/size][/color]
[color=red][size=large]连接sql server[/size][/color]
[color=red][size=large]连接oracle[/size][/color]
[list]
[*]基础很重要,面试常会遇到。
[/list]
package com.xiangxm.javatest.demo;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/*
*<p>
*</p>
*@author xiangxm
*version 1.0
*2013-3-27
*
*
*/
public class ConnectToMySql {
public static final String URL = "jdbc:mysql://localhost:3306/users";
public static final String USER = "root";
public static final String PASSWORD = "admin";
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection(URL, USER,
PASSWORD);
Statement st = connection.createStatement();
String sql = "select * from userInfo";
ResultSet rs = st.executeQuery(sql);
while (rs.next()) {
String loginName = rs.getString(1);
String loginPassword = rs.getString("logpwd");
System.out.print(loginName + " ");
System.out.println(loginPassword);
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("加载驱动失败");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("连接数据库失败");
}
}
}
[color=red][size=large]连接sql server[/size][/color]
package com.xiangxm.javatest.demo;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/*
*<p>
*</p>
*@author xiangxm
*version 1.0
*
*
*/
public class ConnectToSql {
public static final String URL = "jdbc:sqlserver://localhost:1433;databaseName=Northwind";
public static final String USER = "sa";
public static final String PASSWORD = "askme";
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String sql = "select * from Orders";
Connection con = DriverManager.getConnection(URL, USER, PASSWORD);
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(sql);
while (rs.next()) {
int orderId = rs.getInt("OrderID");
System.out.println(orderId);
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("加载驱动失败");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("连接数据库失败");
}
}
}
[color=red][size=large]连接oracle[/size][/color]
package com.javatest.connectdatabase;
import java.sql.*;
public class ConnOracle {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
Class.forName("oracle.jdbc.driver.OracleDriver") ;
System.out.println("加载驱动成功") ;
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("加载驱动失败") ;
}
}}
[list]
[*]基础很重要,面试常会遇到。
[/list]