Skip to content

Instantly share code, notes, and snippets.

@zeroleaf
Created August 28, 2013 16:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zeroleaf/6368246 to your computer and use it in GitHub Desktop.
Save zeroleaf/6368246 to your computer and use it in GitHub Desktop.
The basic operation to connect mysql using java.
import java.sql.*;
public class SqlManipulation
{
private Connection conn;
public SqlManipulation()
{
}
private void init()
{
try
{
//连接数据库
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/dsc", "root", "passwd");
}
catch (ClassNotFoundException e)
{
System.err.println("无法加载数据库驱动!\n" + e.getMessage());
// e.printStackTrace();
}
catch (SQLException e)
{
System.err.println("无法连接数据库.\n" + e.getMessage());
// e.printStackTrace();
}
}
public void DisTableInfo(String sql) throws SQLException
{
init();
Statement stmt = conn.createStatement();
//执行查询语句 获取数据库中的信息
ResultSet rs = stmt.executeQuery(sql);
ResultSetMetaData rsmd = rs.getMetaData();
for (int i = 1; i <= rsmd.getColumnCount(); i++)
{
System.out.print(rsmd.getColumnName(i) + "\t");
System.out.println(rsmd.getColumnTypeName(i));
}
rs.close();
stmt.close();
conn.close();
}
public void DisDatabaseInfo(String sql) throws SQLException
{
init();
//获取数据库的信息
DatabaseMetaData dbmd = conn.getMetaData();
ResultSet rs = dbmd.getTables(null, null, null, new String[ ] { "TABLE" });
while (rs.next())
{
System.out.println("表名:" + rs.getString("TABLE_NAME"));
System.out.println("表所属用户名:" + rs.getString(2));
System.out.println("------------------------------");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment