package MySQL_Base_Operation;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;
public class MySQL {
public static Connection connection;
public static Statement statement;
static {
try {
Class.forName("com.mysql.jdbc.Driver");
connection = java.sql.DriverManager.getConnection("jdbc:mysql://127.0.0.1/temp", "root", "12345678");
statement = connection.createStatement();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void showDatabases(String sql) {
try {
ResultSet rs = statement.executeQuery(sql);
final int col_count = rs.getMetaData().getColumnCount();
while (rs.next()) {
for (int i = 1; i <= col_count; i++) {
System.out.printf("%30s", rs.getString(i));
}
System.out.println();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void handleSQL(String sql) {
int count = -1;
try {
if (sql.contains("show databases")) {
showDatabases(sql);
System.out.println("Query OK.");
} else if (sql.contains("update") || sql.contains("insert") || sql.contains("delete")) {
count = statement.executeUpdate(sql);
System.out.println("Query OK." + count + "rows affected.");
} else if (sql.contains("use")) {
statement.execute(sql);
System.out.println("Database changed.");
} else if (sql.contains("select") || sql.contains("show")) {
ResultSet rs = statement.executeQuery(sql);
final int col_count = rs.getMetaData().getColumnCount();
for (int i = 1; i <= col_count; i++) {
System.out.printf("%32s", rs.getMetaData().getColumnName(i));
}
System.out.println();
while (rs.next()) {
for (int i = 1; i <= col_count; i++) {
System.out.printf("%32s", rs.getString(i));
}
System.out.println();
}
}
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNextLine()) {
String line = sc.nextLine();
if (line != null && !line.equals("")) {
handleSQL(line);
}
}
}
}
数据库连接池简单示例:
jsp访问数据库