一,JDBC连接mysql package jdbc; import java.sql.*; public class jdbcconnection { public static void main(String[] args){ //加载驱动 try { Class.forName("com.mysql.jdbc.Driver"); System.out.println("加载成功"); } catch (ClassNotFoundException e) { e.printStackTrace(); System.out.println("加载失败"); } //连接数据库 //创建连接环境 try { Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/data", "root", "root"); System.out.println("数据库连接成功"); //创建一个Statement Statement statement= conn.createStatement(); //5、执行SQL语句 ResultSet result=statement.executeQuery("select * from user ") ; while(result.next()){ System.out.print(result.getInt("id")+" "); System.out.print(result.getString("uname")+" "); System.out.print(result.getString("upass")+" "); System.out.println(result.getInt("type")+" "); } } catch (SQLException e) { e.printStackTrace(); System.out.println("数据库连接失败"); } } }
一,JDBC连接sqlserver
package text;
import java.sql.*;
public class h1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
//String driverName="com.microsoft.sqlserver.jdbc.SQLServerDriver";
{
String driverName="com.microsoft.sqlserver.jdbc.SQLServerDriver";
String dbURL="jdbc:sqlserver://localhost:1433;DatabaseName=student";
//test为你的数据库名
String userName="sa";//你的数据库用户名
String userPwd="123";//你的密码
try{
//Class.forName();驱动
Class.forName(driverName);
System.out.println("加载驱动成功!");
}catch(Exception e){
e.printStackTrace();
System.out.println("加载驱动失败!");
}
try{
Connection dbConn=DriverManager.getConnection(dbURL,userName,userPwd);
System.out.println("连接数据库成功!");
Statement statement =dbConn.createStatement();
ResultSet result =statement.executeQuery("select * from StudentScorse");
while(result.next()) {
System.out.print(result.getString("id")+" ");
System.out.print(result.getString("name")+" ");
System.out.println(result.getString("value")+" ");
}
}catch(Exception e){
e.printStackTrace();
System.out.print("SQL Server连接失败!");
}
}
}
}