Compare commits

..

No commits in common. "master" and "testk8s" have entirely different histories.

35 changed files with 129 additions and 1236 deletions

11
.classpath Normal file
View File

@ -0,0 +1,11 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" path="src"/>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8"/>
<classpathentry kind="lib" path="lib/kubernetes-assertions-2.2.211.jar"/>
<classpathentry kind="lib" path="lib/jansi-1.16.jar"/>
<classpathentry kind="lib" path="lib/assertj-core-3.8.0.jar"/>
<classpathentry kind="lib" path="lib/fabric8-utils-2.2.211.jar"/>
<classpathentry kind="lib" path="lib/kubernetes-api-2.0.37.jar" sourcepath="lib/kubernetes-api-2.0.37.jar"/>
<classpathentry kind="output" path="bin"/>
</classpath>

17
.project Normal file
View File

@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>TestK8SAPI</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jdt.core.javanature</nature>
</natures>
</projectDescription>

View File

@ -0,0 +1,11 @@
eclipse.preferences.version=1
org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8
org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
org.eclipse.jdt.core.compiler.compliance=1.8
org.eclipse.jdt.core.compiler.debug.lineNumber=generate
org.eclipse.jdt.core.compiler.debug.localVariable=generate
org.eclipse.jdt.core.compiler.debug.sourceFile=generate
org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
org.eclipse.jdt.core.compiler.source=1.8

BIN
bin/com/lqk/k8s/Main.class Normal file

Binary file not shown.

View File

@ -1,4 +0,0 @@
drop database if exists bookstore;
create database bookstore;

View File

@ -1,17 +0,0 @@
drop database if exists bookstore;
create database bookstore;
use bookstore;
create table book(
id int(11) not NULL,
title VARCHAR(255),
author VARCHAR(255),
publisher VARCHAR(255),
publishYear int(11)
)DEFAULT CHARSET=utf8;
Insert into book (id,title,author,publisher,publishYear) values
(1002,'平凡的世界', '路遥','新世界出版社',2011),
(1026,'活着', '余华','东方出版社',2016),
(1204,'围城', '钱钟书','人名文学出版社',1991),
(1208,'围城', '钱钟书','文艺出版社',2012);

View File

@ -1,18 +0,0 @@
drop database if exists bookstore;
create database bookstore;
use bookstore;
create table book(
id int(11) not NULL,
title VARCHAR(255),
author VARCHAR(255),
publisher VARCHAR(255),
publishYear int(11)
)DEFAULT CHARSET=utf8;
Insert into book (id,title,author,publisher,publishYear) values
(1002,'平凡的世界', '路遥','新世界出版社',2011),
(1026,'活着', '余华','东方出版社',2016),
(1204,'围城', '钱钟书','人名文学出版社',1991),
(1208,'围城', '钱钟书','文艺出版社',2012),
(1004,'平凡的世界', '路遥','文艺出版社',2012),
(1010,'人生', '路遥','文艺出版社',2005),
(1024,'活着', '余华','作家出版社',2012);

View File

@ -1,16 +0,0 @@
drop database if exists bookstore;
create database bookstore;
use bookstore;
create table book(
id int(11) not NULL,
title VARCHAR(255),
author VARCHAR(255),
publisher VARCHAR(255),
publishYear int(11)
)DEFAULT CHARSET=utf8;
Insert into book (id,title,author,publisher,publishYear) values
(1002,'平凡的世界', '路遥','新世界出版社',2011),
(1204,'围城', '钱钟书','人名文学出版社',1991),
(1208,'围城', '钱钟书','文艺出版社',2012),
(1004,'平凡的世界', '路遥','文艺出版社',2012),
(1010,'人生', '路遥','文艺出版社',2005);

View File

@ -1,16 +0,0 @@
drop database if exists bookstore;
create database bookstore;
use bookstore;
create table book(
id int(11) not NULL,
title VARCHAR(255),
author VARCHAR(255),
publisher VARCHAR(255),
publishYear int(11)
)DEFAULT CHARSET=utf8;
Insert into book (id,title,author,publisher,publishYear) values
(1002,'平凡的世界', '路遥','新世界出版社',2011),
(1204,'围城', '钱钟书','人名文学出版社',1991),
(1208,'围城', '钱钟书','文艺出版社',2012),
(1004,'平凡的世界', '路遥','文艺出版社',2012),
(1010,'人生', '路遥','文艺出版社',2005);

View File

@ -1,18 +0,0 @@
drop database if exists bookstore;
create database bookstore;
use bookstore;
create table step7(
id int(11) not NULL,
title VARCHAR(255),
author VARCHAR(255),
publisher VARCHAR(255),
publishYear int(11)
)DEFAULT CHARSET=utf8;
Insert into step7 (id,title,author,publisher,publishYear) values
(1002,'平凡的世界', null,'新世界出版社',null),
(1208,null, '钱钟书',null,null);
create table transformedBook(
id int(11),
column_name VARCHAR(255),
value VARCHAR(255)
)DEFAULT CHARSET=utf8;

Binary file not shown.

BIN
lib/assertj-core-3.8.0.jar Normal file

Binary file not shown.

Binary file not shown.

BIN
lib/jansi-1.16.jar Normal file

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

90
src/com/lqk/k8s/Main.java Normal file
View File

@ -0,0 +1,90 @@
package com.lqk.k8s;
import java.util.ArrayList;
import io.fabric8.kubernetes.api.KubernetesClient;
import io.fabric8.kubernetes.api.KubernetesFactory;
import io.fabric8.kubernetes.api.model.*;
import io.fabric8.kubernetes.*;
import io.fabric8.*;
public class Main {
private String ip;
private String port;
public Main(String ip, String port) {
this.ip= ip;
this.port = port;
}
public KubernetesClient getConnection() {
final String URI = "http://" + ip+ ":" + port;
final KubernetesClient kubernetes = new KubernetesClient(new KubernetesFactory(URI));
return kubernetes;
}
public List<KubePodModel> getKubePods() {
List<KubePodModel> kubePodList = new ArrayList<KubePodModel>();
for (Pod pod : kubernetes.getPods().getItems()) {
KubePodModel model = new KubePodModel();
model.setId(pod.getId());
model.setApiVersion(pod.getApiVersion());
model.setCreationTime(pod.getCreationTimestamp());
model.setNamespace(pod.getNamespace());
model.setPodHostName(pod.getCurrentState().getHost());
model.setPodIp(pod.getCurrentState().getPodIP());
model.setStatus(pod.getCurrentState().getStatus());
kubePodList.add(podModel);
}
return kubePodModelList;
}
public void createKubePod(String id, String namespace, List<String> containerPorts, String image, Map<String, String> labels) {
Pod pod = new Pod();
pod.setId(id);
pod.setLabels(labels);
PodState desiredState = new PodState();
ContainerManifest manifest = new ContainerManifest();
Container manifestContainer = new Container();
manifestContainer.setName(podId);
manifestContainer.setImage(image);
List<Port> ports = new ArrayList<Port>();
for (String containerInputPort : containerPorts) {
CharSequence inputStr = containerInputPort;
String patternStr = "(\\S+):(\\S+)";
Pattern pattern = Pattern.compile(patternStr);
Matcher matcher = pattern.matcher(inputStr);
boolean matchFound = matcher.find();
if (matchFound) {
int contanierPort = Integer.valueOf(matcher.group(1));
String containerProto = matcher.group(2);
Port port = new Port();
port.setContainerPort(contanierPort);
port.setProtocol(containerProto);
ports.add(port);
}
}
manifestForContainer.setPorts(ports);
List<Container> containers = new ArrayList<>();
containers.add(manifestForContainer);
manifest.setContainers(containers);
desiredState.setManifest(manifest);
pod.setDesiredState(desiredState);
kubernetes.createPod(pod, namespace);
}
}

View File

@ -1,83 +0,0 @@
package step1;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class MySQLWithJDBC {
// 设定JDBC驱动以及本地数据库的URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql:///?useUnicode=true&characterEncoding=utf-8";
// 指定数据库的用户名和密码
static final String USER = "root";
static final String PASS = "123123";
// 建立与指定数据库的连接并返回该连接
public Connection getConnection(String jdbc_driver, String db_url, String db_user, String db_passwd) {
Connection connection = null;
//注册JDBC驱动
try {
Class.forName(jdbc_driver);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
//创建于指定数据库的连接
try {
connection = DriverManager.getConnection(db_url, db_user, db_passwd);
} catch (SQLException e) {
e.printStackTrace();
}
return connection;
}
//创建数据库实例
public void createDatabaseInstance(Connection connection, String databaseName){
Statement stmt = null;
//请在此处补全创建数据库实例的SQL语句
String sqlScript = "create database " + databaseName;
try {
stmt = (Statement) connection.createStatement();
stmt.executeUpdate(sqlScript);
} catch (SQLException e) {
e.printStackTrace();
}
}
//创建数据库实例
public void dropDatabase(Connection connection, String databaseName){
Statement stmt = null;
//请在此处补全创建数据库实例的SQL语句
String sqlScript = "drop database if exists " + databaseName;
try {
stmt = (Statement) connection.createStatement();
stmt.executeUpdate(sqlScript);
} catch (SQLException e) {
e.printStackTrace();
}
}
//获取数据库中已经存在的数据库实例
public ResultSet getExistDB(Connection connection, String databaseName) throws SQLException
{
ResultSet resultSet = null;
Statement stmt = null;
String sqlScript = "SELECT * FROM information_schema.SCHEMATA where SCHEMA_NAME=\"" + databaseName + "\"";
try {
stmt = (Statement) connection.createStatement();
resultSet = stmt.executeQuery(sqlScript);
} catch (SQLException e) {
e.printStackTrace();
}
return resultSet;
}
}

View File

@ -1,40 +0,0 @@
package step1;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;
public class MySQLWithJDBCTest {
public static void main(String[] args) throws SQLException {
MySQLWithJDBC mysql = new MySQLWithJDBC();
String databaseName = "";
//从命令行接收输入获得数据库的名字
Scanner sc = new Scanner(System.in);
databaseName = sc.next();
//建立数据库连接
Connection connection = mysql.getConnection(mysql.JDBC_DRIVER, mysql.DB_URL, mysql.USER, mysql.PASS);
mysql.dropDatabase(connection,databaseName);
//执行创建数据库的命令
mysql.createDatabaseInstance(connection, databaseName);
//查询数据库验证是否成功创建
ResultSet result = mysql.getExistDB(connection, databaseName);
//获取查询结果
while(result.next())
{
String dbName = result.getString("SCHEMA_NAME");
System.out.print("databaseName:" + dbName);
}
}
}

View File

@ -1,108 +0,0 @@
package step2;
import java.io.FileInputStream;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
public class CreateTable {
// 设定JDBC驱动以及本地数据库的URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql:///bookstore?useUnicode=true&characterEncoding=utf-8";
// 指定数据库的用户名和密码
static final String USER = "root";
static final String PASS = "123123";
// 建立与指定数据库的连接并返回该连接
public Connection getConnection(String jdbc_driver, String db_url, String db_user, String db_passwd) {
Connection connection = null;
//注册JDBC驱动
try {
Class.forName(jdbc_driver);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
//创建于指定数据库的连接
try {
connection = (Connection) DriverManager.getConnection(db_url, db_user, db_passwd);
} catch (SQLException e) {
e.printStackTrace();
}
return connection;
}
//在指定数据库实例中创建有tableName命名的表
public void createTable(Connection connection, String tableName,String[][] tableInfo){
//请在此处实现创建表的操作
String sqlScript = "create table " + tableName + "(\n";
Statement stmt = null;
for(int k=0;k<tableInfo.length;k++)
{
if(tableInfo[k][0].equals(""))
break;
System.out.println(tableInfo[k][0] + tableInfo[k][1]);
sqlScript = sqlScript + tableInfo[k][0] + " " + tableInfo[k][1] + ",\n";
}
sqlScript = sqlScript.substring(0, sqlScript.length()-2);
sqlScript = sqlScript + ")";
try {
stmt = connection.createStatement();
stmt.executeUpdate(sqlScript);
} catch (SQLException e) {
e.printStackTrace();
}
}
public ResultSet getExistTable(Connection conn,String databaseName,String tableName) {
ResultSet resultSet = null;
Statement stmt = null;
/*select TABLE_NAME from INFORMATION_SCHEMA.TABLES whereTABLE_SCHEMA='dbname' and TABLE_NAME='tablename' ;*/
String sqlScript = "select * from INFORMATION_SCHEMA.TABLES where TABLE_SCHEMA=\'" +databaseName +
"\' and TABLE_NAME=\'" + tableName + "\'";
try {
stmt = (Statement) conn.createStatement();
resultSet = stmt.executeQuery(sqlScript);
} catch (SQLException e) {
e.printStackTrace();
}
return resultSet;
}
List<String> loadSql(String sqlFile) throws Exception {
List<String> sqlList = new ArrayList<String>();
try {
InputStream sqlFileIn = new FileInputStream(sqlFile);
StringBuffer sqlSb = new StringBuffer();
byte[] buff = new byte[1024];
int byteRead = 0;
while ((byteRead = sqlFileIn.read(buff)) != -1) {
sqlSb.append(new String(buff, 0, byteRead));
} // Windows 下换行是 \r\n, Linux 下是 \n
String[] sqlArr = sqlSb.toString().split("(;\\s*\\r\\n)(;\\s*\\n)");
for (int i = 0; i < sqlArr.length; i++) {
String sql = sqlArr[i].replaceAll("--.*", "").trim();
if (!sql.equals("")) {
sqlList.add(sql);
}
}
return sqlList;
} catch (Exception ex) {
throw new Exception(ex.getMessage());
}
}
}

View File

@ -1,102 +0,0 @@
package step2;
import java.util.List;
import java.util.Scanner;
import java.util.logging.Logger;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.taskdefs.SQLExec;
import java.io.File;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class CreateTableTest {
Scanner sc = new Scanner(System.in);
String tableName =sc.nextLine().trim();
int fieldNum = Integer.parseInt(sc.nextLine().trim());
String[][]TableInfo = initTableInfo(fieldNum);
int arrayIndex=0;
String fieldName="";
String prop="";
while(true)
{
String input = sc.nextLine();
if(input.equals(""))
break;
String[]info = input.split(" ");
if(info.length != 2)
{
break;
}
//字段名
fieldName = info[0];
prop = info[1];
TableInfo[arrayIndex][0] = fieldName;
TableInfo[arrayIndex][1] = prop;
arrayIndex = arrayIndex + 1;
if(arrayIndex > fieldNum-1)
break;
}
CreateTable createTable = new CreateTable();
/*
* 执行初始化脚本F:\test.sql
* 执行初始化脚连接数据库时不需要指定数据库
*/
String sqlFile=System.getProperty("user.dir")+File.separator+"challenge2.sql";
SQLExec sqlExec = new SQLExec();
//设置数据库参数
sqlExec.setDriver(createTable.JDBC_DRIVER);
sqlExec.setUrl("jdbc:mysql://localhost/");
sqlExec.setUserid(createTable.USER);
sqlExec.setPassword(createTable.PASS);
try
{
//要执行的脚本
sqlExec.setSrc(new File(sqlFile));
sqlExec.setProject(new Project()); // 要指定这个属性不然会出错
sqlExec.execute();
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
//将连接定位到bookStore数据库
Connection connection = createTable.getConnection(createTable.JDBC_DRIVER, createTable.DB_URL, createTable.USER, createTable.PASS);
createTable.createTable(connection, tableName,TableInfo);
//再次查询数据库检查是否成功创建指定的表
ResultSet result = createTable.getExistTable(connection,"bookStore",tableName);
while(result.next())
{
String table = result.getString("TABLE_NAME");
System.out.print("table:"+table);
}
}
public static String[][] initTableInfo(int rowNum)
{
String[][] tmp = new String[rowNum][2];
for(int i=0;i<rowNum;i++)
{
for(int j=0;j<2;j++)
tmp[i][j] = "";
}
return tmp;
}
}

View File

@ -1,115 +0,0 @@
package step3;
import java.io.FileInputStream;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class InsertTable {
public void InsertRecord(Connection connection, int id, String title, String author, String publisher, int year){
//在此添加插入数据的操作
Statement stmt = null;
String sqlScript = "Insert into book(id,title,author,publisher,publishYear) values" + "(" + id +"," +
"\'" + title+ "\',\'" + author + "\',\'" + publisher + "\',\'" + year + "\')";
try {
stmt = connection.createStatement();
stmt.executeUpdate(sqlScript);
} catch (SQLException e) {
e.printStackTrace();
}
}
// 设定JDBC驱动以及本地数据库的URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql:///bookstore?useUnicode=true&characterEncoding=utf-8";
// 指定数据库的用户名和密码
static final String USER = "root";
static final String PASS = "123123";
// 建立与指定数据库的连接并返回该连接
public Connection getConnection(String jdbc_driver, String db_url, String db_user, String db_passwd) {
Connection connection = null;
//注册JDBC驱动
try {
Class.forName(jdbc_driver);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
//创建于指定数据库的连接
try {
connection = (Connection) DriverManager.getConnection(db_url, db_user, db_passwd);
} catch (SQLException e) {
e.printStackTrace();
}
return connection;
}
public ResultSet queryDB(Connection connection,String tableName) {
ResultSet result = null;
Statement stmt = null;
String sqlScript = "select * from " + tableName + " order by id desc";
try {
stmt = connection.createStatement();
result = stmt.executeQuery(sqlScript);
} catch (SQLException e) {
e.printStackTrace();
}
return result;
}
//创建数据库实例
public void createDatabaseInstance(Connection connection, String databaseName){
Statement stmt = null;
//请在此处补全创建数据库实例的SQL语句
String sqlScript = "";
try {
stmt = (Statement) connection.createStatement();
stmt.executeUpdate(sqlScript);
} catch (SQLException e) {
e.printStackTrace();
}
}
List<String> loadSql(String sqlFile) throws Exception {
List sqlList = new ArrayList();
try {
InputStream sqlFileIn = new FileInputStream(sqlFile);
StringBuffer sqlSb = new StringBuffer();
byte[] buff = new byte[1024];
int byteRead = 0;
while ((byteRead = sqlFileIn.read(buff)) != -1) {
sqlSb.append(new String(buff, 0, byteRead));
} // Windows 下换行是 \r\n, Linux 下是 \n
String[] sqlArr = sqlSb.toString().split("(;\\s*\\r\\n)(;\\s*\\n)");
for (int i = 0; i < sqlArr.length; i++) {
String sql = sqlArr[i].replaceAll("--.*", "").trim();
if (!sql.equals("")) {
sqlList.add(sql);
}
}
return sqlList;
} catch (Exception ex) {
throw new Exception(ex.getMessage());
}
}
}

View File

@ -1,77 +0,0 @@
package step3;
import java.util.List;
import java.util.Scanner;
import java.awt.print.Printable;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.io.*;
import org.apache.tools.ant.*;
import org.apache.tools.ant.taskdefs.*;
import org.apache.tools.ant.taskdefs.condition.Equals;
import org.apache.tools.ant.types.*;
public class InsertTableTest {
public static void main(String[] args) throws Exception {
String tableName = "book";
InsertTable insertTable = new InsertTable();
String sqlFile=System.getProperty("user.dir")+File.separator+"challenge3.sql";
SQLExec sqlExec = new SQLExec();
//设置数据库参数
sqlExec.setDriver(insertTable.JDBC_DRIVER);
sqlExec.setUrl("jdbc:mysql://localhost/");
sqlExec.setUserid(insertTable.USER);
sqlExec.setPassword(insertTable.PASS);
try
{
//要执行的脚本
sqlExec.setSrc(new File(sqlFile));
sqlExec.setProject(new Project()); // 要指定这个属性不然会出错
sqlExec.execute();
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
Connection connection = insertTable.getConnection(insertTable.JDBC_DRIVER, insertTable.DB_URL, insertTable.USER, insertTable.PASS);
Scanner sc = new Scanner(System.in);
while(true)
{
String input = sc.nextLine();
if(input.equals(""))
break;
String[]commands = input.split(" ");
if(commands.length ==0)
break;
int id = Integer.parseInt(commands[0]);
String title = commands[1];
String author = commands[2];
String publisher = commands[3];
int year = Integer.parseInt(commands[4]);
insertTable.InsertRecord(connection, id,title,author,publisher,year);
}
ResultSet result = insertTable.queryDB(connection, tableName);
while (result.next()) {
String id = result.getString("id");
String title= result.getString("title");
String author = result.getString("author");
String publisher = result.getString("publisher");
String publishYear = result.getString("publishYear");
System.out.println(id + " " + title+ " " + author + " "
+ publisher + " " + publishYear);
}
}
}

View File

@ -1,88 +0,0 @@
package step4;
import java.io.File;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class DeleteRecord {
public int deleteRecordByAuthor(Connection connection, String tableName,String author)
{
Statement stmt = null;
int updatedNum = 0;
//请在此处添加数据库删除记录的实现代码
String sqlScript = "delete from " + tableName + " where author = \'" + author + "\'";
try {
stmt = connection.createStatement();
updatedNum = stmt.executeUpdate(sqlScript);
} catch (SQLException e) {
e.printStackTrace();
}
return updatedNum;
}
// 设定JDBC驱动以及本地数据库的URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql:///bookstore?useUnicode=true&characterEncoding=utf-8";
// 指定数据库的用户名和密码
static final String USER = "root";
static final String PASS = "123123";
// 建立与指定数据库的连接并返回该连接
public Connection getConnection(String jdbc_driver, String db_url, String db_user, String db_passwd) {
Connection connection = null;
//注册JDBC驱动
try {
Class.forName(jdbc_driver);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
//创建于指定数据库的连接
try {
connection = (Connection) DriverManager.getConnection(db_url, db_user, db_passwd);
} catch (SQLException e) {
e.printStackTrace();
}
return connection;
}
//创建数据库实例
public void createDatabaseInstance(Connection connection, String databaseName){
Statement stmt = null;
//请在此处补全创建数据库实例的SQL语句
String sqlScript = "";
try {
stmt = (Statement) connection.createStatement();
stmt.executeUpdate(sqlScript);
} catch (SQLException e) {
e.printStackTrace();
}
}
public ResultSet queryDB(Connection connection,String tableName) {
ResultSet result = null;
Statement stmt = null;
String sqlScript = "select * from " + tableName + " order by id desc";
try {
stmt = connection.createStatement();
result = stmt.executeQuery(sqlScript);
} catch (SQLException e) {
e.printStackTrace();
}
return result;
}
}

View File

@ -1,67 +0,0 @@
package step4;
import java.util.Scanner;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.io.*;
import org.apache.tools.ant.*;
import org.apache.tools.ant.taskdefs.*;
import org.apache.tools.ant.types.*;
public class DeleteRecordTest {
public static void main(String[] args) throws SQLException {
String tableName ="book";
String authorName = "";
Scanner sc = new Scanner(System.in);
authorName = sc.nextLine();
DeleteRecord deleteTable = new DeleteRecord();
SQLExec sqlExec = new SQLExec();
//设置数据库参数
sqlExec.setDriver(deleteTable.JDBC_DRIVER);
sqlExec.setUrl("jdbc:mysql://localhost/");
sqlExec.setUserid(deleteTable.USER);
sqlExec.setPassword(deleteTable.PASS);
String sqlFile=System.getProperty("user.dir")+File.separator+"challenge4.sql";
try
{
//要执行的脚本
sqlExec.setSrc(new File(sqlFile));
sqlExec.setProject(new Project()); // 要指定这个属性不然会出错
sqlExec.execute();
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
Connection connection = deleteTable.getConnection(deleteTable.JDBC_DRIVER, deleteTable.DB_URL, deleteTable.USER, deleteTable.PASS);
int updatedNum = deleteTable.deleteRecordByAuthor(connection,tableName,authorName);
//updatedNum=0说明删除的行数为0删除失败
if(updatedNum == 0)
{
System.out.println(0);
return;
}
ResultSet result = deleteTable.queryDB(connection, tableName);
while (result.next()) {
String id = result.getString("id");
String title= result.getString("title");
String author = result.getString("author");
String publisher = result.getString("publisher");
String publishYear = result.getString("publishYear");
System.out.println(id + " " + title+ " " + author + " "
+ publisher + " " + publishYear);
}
}
}

View File

@ -1,70 +0,0 @@
package step5;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class QueryRecord {
public ResultSet queryPublisherByBookName(Connection connection, String tableName,String bookName)
{
//请在此处查询表的操作
Statement stmt = null;
ResultSet result = null;
String sqlScript = "select distinct(publisher) from " + tableName + " where title = '" + bookName + "\'";
try {
stmt = connection.createStatement();
result = stmt.executeQuery(sqlScript);
} catch (SQLException e) {
e.printStackTrace();
}
return result;
}
// 设定JDBC驱动以及本地数据库的URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql:///bookstore?useUnicode=true&characterEncoding=utf-8";
// 指定数据库的用户名和密码
static final String USER = "root";
static final String PASS = "123123";
// 建立与指定数据库的连接并返回该连接
public Connection getConnection(String jdbc_driver, String db_url, String db_user, String db_passwd) {
Connection connection = null;
//注册JDBC驱动
try {
Class.forName(jdbc_driver);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
//创建于指定数据库的连接
try {
connection = (Connection) DriverManager.getConnection(db_url, db_user, db_passwd);
} catch (SQLException e) {
e.printStackTrace();
}
return connection;
}
//创建数据库实例
public void createDatabaseInstance(Connection connection, String databaseName){
Statement stmt = null;
//请在此处补全创建数据库实例的SQL语句
String sqlScript = "";
try {
stmt = (Statement) connection.createStatement();
stmt.executeUpdate(sqlScript);
} catch (SQLException e) {
e.printStackTrace();
}
}
}

View File

@ -1,54 +0,0 @@
package step5;
import java.io.File;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.*;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.taskdefs.SQLExec;
public class QueryRecordTest {
public static void main(String[] args) throws SQLException {
String tableName = "book";
String bookName = "";
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
String[] queryInfo = input.split(" ");
if(queryInfo.length != 1)
{
System.out.println("参数输入错误");
return;
}
bookName = queryInfo[0];
QueryRecord queryRecord = new QueryRecord();
String sqlFile=System.getProperty("user.dir")+File.separator+"challenge4.sql";
SQLExec sqlExec = new SQLExec();
//设置数据库参数
sqlExec.setDriver(queryRecord.JDBC_DRIVER);
sqlExec.setUrl("jdbc:mysql://localhost/");
sqlExec.setUserid(queryRecord.USER);
sqlExec.setPassword(queryRecord.PASS);
try
{
//要执行的脚本
sqlExec.setSrc(new File(sqlFile));
sqlExec.setProject(new Project()); // 要指定这个属性不然会出错
sqlExec.execute();
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
Connection connection = queryRecord.getConnection(queryRecord.JDBC_DRIVER, queryRecord.DB_URL, queryRecord.USER, queryRecord.PASS);
ResultSet result = queryRecord.queryPublisherByBookName(connection, tableName,bookName);
while(result.next())
{
String id = result.getString("publisher");
System.out.println("publisher:" + id);
}
}
}

View File

@ -1,86 +0,0 @@
package step6;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.io.*;
import org.apache.tools.ant.*;
import org.apache.tools.ant.taskdefs.*;
import org.apache.tools.ant.types.*;
public class UpdateRecord {
public int updatePublisherByTitle(Connection connection,String tableName, String title, String publisher){
//请在此处实现数据更新功能
Statement stmt = null;
int updatedNum=0;
String sqlScript = "update " + tableName + " set publisher=\'" +publisher + "\' where title=\'" + title + "'";
try {
stmt = connection.createStatement();
updatedNum = stmt.executeUpdate(sqlScript);
} catch (SQLException e) {
e.printStackTrace();
}
return updatedNum;
}
// 设定JDBC驱动以及本地数据库的URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql:///bookstore?useUnicode=true&characterEncoding=utf-8";
// 指定数据库的用户名和密码
static final String USER = "root";
static final String PASS = "123123";
// 建立与指定数据库的连接并返回该连接
public Connection getConnection(String jdbc_driver, String db_url, String db_user, String db_passwd) {
Connection connection = null;
//注册JDBC驱动
try {
Class.forName(jdbc_driver);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
//创建于指定数据库的连接
try {
connection = (Connection) DriverManager.getConnection(db_url, db_user, db_passwd);
} catch (SQLException e) {
e.printStackTrace();
}
return connection;
}
//创建数据库实例
public void createDatabaseInstance(Connection connection, String databaseName){
Statement stmt = null;
//请在此处补全创建数据库实例的SQL语句
String sqlScript = "";
try {
stmt = (Statement) connection.createStatement();
stmt.executeUpdate(sqlScript);
} catch (SQLException e) {
e.printStackTrace();
}
}
public ResultSet queryDB(Connection connection,String tableName) {
ResultSet result = null;
Statement stmt = null;
String sqlScript = "select * from " + tableName + " order by id desc";
try {
stmt = connection.createStatement();
result = stmt.executeQuery(sqlScript);
} catch (SQLException e) {
e.printStackTrace();
}
return result;
}
}

View File

@ -1,69 +0,0 @@
package step6;
import java.util.Scanner;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.io.*;
import org.apache.tools.ant.*;
import org.apache.tools.ant.taskdefs.*;
import org.apache.tools.ant.types.*;
public class UpdateRecordTest {
public static void main(String args[]) throws SQLException {
String tableName = "book";
UpdateRecord updateRecord = new UpdateRecord();
String sqlFile=System.getProperty("user.dir")+File.separator+"challenge6.sql";
SQLExec sqlExec = new SQLExec();
//设置数据库参数
sqlExec.setDriver(updateRecord.JDBC_DRIVER);
sqlExec.setUrl("jdbc:mysql://localhost/");
sqlExec.setUserid(updateRecord.USER);
sqlExec.setPassword(updateRecord.PASS);
try
{
//要执行的脚本
sqlExec.setSrc(new File(sqlFile));
sqlExec.setProject(new Project()); // 要指定这个属性不然会出错
sqlExec.execute();
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
Connection connection = updateRecord.getConnection(updateRecord.JDBC_DRIVER, updateRecord.DB_URL, updateRecord.USER, updateRecord.PASS);
Scanner scanner = new Scanner(System.in);
while(true)
{
String input = scanner.nextLine();
if(input.equals(""))
break;
String[]commands = input.split(" ");
if(commands.length ==0 || commands.length != 2)
break;
String title = commands[0];
String publisher = commands[1];
int updatedNum = updateRecord.updatePublisherByTitle(connection, tableName,title,publisher);
}
ResultSet result = updateRecord.queryDB(connection, tableName);
while (result.next()) {
String id = result.getString("id");
String title= result.getString("title");
String author = result.getString("author");
String publisher = result.getString("publisher");
String publishYear = result.getString("publishYear");
System.out.println(id + " " + title+ " " + author + " "
+ publisher + " " + publishYear);
}
}
}

View File

@ -1,125 +0,0 @@
package step7;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.naming.spi.DirStateFactory.Result;
public class TransferTable {
public void transferTable(Connection connection, String tableName) throws SQLException{
//请在此将转换表结构的函数补充完整
ResultSet result = null;
Statement stmt = null;
String sqlScript = "select * from " + tableName + " order by id desc";
try {
stmt = connection.createStatement();
result = stmt.executeQuery(sqlScript);
} catch (SQLException e) {
e.printStackTrace();
}
String sqlScrript = "insert into transformedBook (id,column_name,value) values (";
while (result.next()) {
String sql = "";
String id = result.getString("id");
String title= result.getString("title");
if(title != null)
{
sql = sqlScript + id + ",'" + "title" + "','" + title + "');";
InsertRecord(connection, sql);
}
String author = result.getString("author");
if(author != null)
{
sql = sqlScript + id + ",'" + "author" + "','" + author + "');";
InsertRecord(connection, sql);
}
String publisher = result.getString("publisher");
if(publisher != null)
{
sql = sqlScript + id + ",'" + "publisher" + "','" + publisher + "');";
InsertRecord(connection, sql);
}
String publishYear = result.getString("publishYear");
if(publishYear != null)
{
sql = sqlScript + id + ",'" + "publishYear" + "','" + publishYear + "');";
InsertRecord(connection, sql);
}
}
}
public void InsertRecord(Connection connection,String sqlScript){
Statement stmt = null;
try {
stmt = connection.createStatement();
stmt.executeUpdate(sqlScript);
} catch (SQLException e) {
e.printStackTrace();
}
}
public ResultSet queryDB(Connection connection, String tableName){
//请在此处查询表的操作
Statement stmt = null;
ResultSet result = null;
String sqlScript = "select * from " + tableName;
try {
stmt = connection.createStatement();
result = stmt.executeQuery(sqlScript);
} catch (SQLException e) {
e.printStackTrace();
}
return result;
}
// 设定JDBC驱动以及本地数据库的URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql:///bookstore?useUnicode=true&characterEncoding=utf-8";
// 指定数据库的用户名和密码
static final String USER = "root";
static final String PASS = "123123";
// 建立与指定数据库的连接并返回该连接
public Connection getConnection(String jdbc_driver, String db_url, String db_user, String db_passwd) {
Connection connection = null;
//注册JDBC驱动
try {
Class.forName(jdbc_driver);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
//创建于指定数据库的连接
try {
connection = (Connection) DriverManager.getConnection(db_url, db_user, db_passwd);
} catch (SQLException e) {
e.printStackTrace();
}
return connection;
}
//创建数据库实例
public void createDatabaseInstance(Connection connection, String databaseName){
Statement stmt = null;
//请在此处补全创建数据库实例的SQL语句
String sqlScript = "";
try {
stmt = (Statement) connection.createStatement();
stmt.executeUpdate(sqlScript);
} catch (SQLException e) {
e.printStackTrace();
}
}
}

View File

@ -1,63 +0,0 @@
package step7;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;
import java.io.*;
import org.apache.tools.ant.*;
import org.apache.tools.ant.taskdefs.*;
import org.apache.tools.ant.types.*;
public class TransferTableTest {
public static void main(String args[]) throws SQLException {
TransferTable transferTable = new TransferTable();
//原始的表名
String tableName = "book";
//转换后的表名
String transferTableName = "transformedBook";
//获取初始化的sql脚本
String sqlFile=System.getProperty("user.dir")+File.separator+"challenge7.sql";
SQLExec sqlExec = new SQLExec();
//设置数据库参数
sqlExec.setDriver(transferTable.JDBC_DRIVER);
sqlExec.setUrl("jdbc:mysql://localhost/");
sqlExec.setUserid(transferTable.USER);
sqlExec.setPassword(transferTable.PASS);
try
{
//要执行的脚本
sqlExec.setSrc(new File(sqlFile));
sqlExec.setProject(new Project()); // 要指定这个属性不然会出错
sqlExec.execute();
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
Connection connection = transferTable.getConnection(transferTable.JDBC_DRIVER, transferTable.DB_URL, transferTable.USER, transferTable.PASS);
transferTable.transferTable(connection, tableName);
//查询数据库中转换后的表输出其内容以判断操作转换操作是否正确
ResultSet resultSet = transferTable.queryDB(connection, transferTableName);
while(resultSet.next())
{
String id = resultSet.getString("id");
String columnName = resultSet.getString("columnName");
String value = resultSet.getString("value");
//注意这里每行后有换行即最后一行后有换行
System.out.println(id + " " + columnName + " " + value);
}
}
}

View File

View File