连接之前的准备
1.mysql的jar包
2.MySQL数据库的连接地址、账号、密码
主要使用到的类
Connection
Statement或者PreparedStatement(原则上使用PreparedStatement)
ResultSet
ResultSetMetaData
如果要连接其他的数据库,需要把jar包和加载的驱动修改成对应的数据库。
下面是代码
/**
* @author kuan
* Created on 2018/8/27.
* @description
*/
public class MySqlControl {
//远程数据库账号
public static final String SQLITEURL = "jdbc:mysql://192.168.6.221:3306/tmdb";
//远程数据库账号
public static final String SQLITEUSER = "appuser";
//远程数据库密码
public static final String SQLITEPW = "0606";
public static Connection connection;
public static void main(String[] args) throws SQLException {
try {
Class.forName("com.mysql.jdbc.Driver");
connection = (Connection) DriverManager.getConnection(SQLITEURL, SQLITEUSER, SQLITEPW);
if (connection == null) {
connection = (Connection) DriverManager.getConnection(SQLITEURL, SQLITEUSER, SQLITEPW);
}
} catch (ClassNotFoundException e) {
Logger.e("连接数据库错误=========" + e.toString());
e.printStackTrace();
} catch (SQLException e) {
Logger.e("数据库错误=========" + e.toString());
e.printStackTrace();
//sql语句
String sqlMessage = "insert into user(name,age,sex) values(?,?,?)";
//获取查询的字段
String keyWord = "";
// PreparedStatement preparedStatement = (PreparedStatement) connection.prepareStatement(sqlMessage);
// preparedStatement.setString(1,"");
// preparedStatement.setString(2,"");
// preparedStatement.setString(3,"");
// // 执行更新操作
// preparedStatement.executeUpdate();
Statement statement = (Statement) connection.createStatement();
ResultSet resultSet = statement.executeQuery(sqlMessage);
ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
int columns = resultSetMetaData.getColumnCount();
//显示列,表格的表头
for (int i = 1; i <= columns; i++) {
System.out.print(resultSetMetaData.getColumnName(i));
System.out.print("\t\t");
}
System.out.println();
//显示表格内容
while (resultSet.next()) {
for (int i = 1; i <= columns; i++) {
System.out.print(resultSet.getString(i));
System.out.print("\t\t");
}
System.out.println();
}
}
}
}
网友评论