最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
java怎么用mysql JAVA操作mysql的教程
时间:2017-02-16 编辑:简简单单 来源:一聚教程网
所需jar包:mysql-connector-java.jar
代码:
代码如下 | 复制代码 |
import java.sql.*; import java.util.ArrayList; import java.util.HashMap; import java.util.List;
import com.mysql.jdbc.Connection; import com.mysql.jdbc.Statement;
public class ConnectMySQL {
public static String driver = "com.mysql.jdbc.Driver";
private static String host;
private static String user;
private static String pwd;
private static Connection conn = null;
private static Statement stmt = null;
public static void connect(String host, String user, String pwd) { ConnectMySQL.close(); ConnectMySQL.host = host; ConnectMySQL.user = user; ConnectMySQL.pwd = pwd; }
public static synchronized List return ConnectMySQL.result(sql); }
public static synchronized void close() { try { if (stmt != null) { stmt.close(); stmt = null; } if (conn != null) { conn.close(); conn = null; } } catch (SQLException e) { e.printStackTrace(); } }
private static void connectMySQL() { try { Class.forName(driver).newInstance(); conn = (Connection) DriverManager.getConnection("jdbc:mysql://" + host + "?useUnicode=true&characterEncoding=UTF8", user, pwd); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); }
}
private static void statement() { if (conn == null) { ConnectMySQL.connectMySQL(); } try { stmt = (Statement) conn.createStatement(); } catch (SQLException e) { e.printStackTrace(); } }
private static ResultSet resultSet(String sql) { ResultSet rs = null; if (stmt == null) { ConnectMySQL.statement(); } try { rs = stmt.executeQuery(sql); } catch (SQLException e) { e.printStackTrace(); } return rs; }
private static List ResultSet rs = ConnectMySQL.resultSet(sql); List try { ResultSetMetaData md = rs.getMetaData(); int cc = md.getColumnCount(); while (rs.next()) { HashMap for (int i = 1; i <= cc; i++) { columnMap.put(md.getColumnName(i), rs.getString(i)); } result.add(columnMap); } } catch (SQLException e) { e.printStackTrace(); } return result; }
public static void main(String[] args) throws SQLException { ConnectMySQL .connect("192.168.1.1/test", "test", "test"); List .query("SELECT * from test"); System.out.println(rs.get(0).get("test")); ConnectMySQL.close(); } } |
-
上一个: java怎么学数据挖掘?
相关文章
- mysql下mysqladmin日常管理命令总结(必看篇) 07-25
- 查看当前mysql使用频繁的sql语句(详解) 07-11
- 对MySql经常使用语句的全面总结(必看篇) 07-11
- 关于mysql init_connect的几个要点总结 07-10
- MySQL外键约束的禁用与启用命令 07-06
- Python使用pymysql小技巧 06-07