Java 设置FirstName=FirstName,LastName=LastName+ “其中AuthorID=AuthorID)”; } //插入标题 如果(选项==3) { query=“插入标题(ISBN、标题、编辑编号、版权)”+ “价值(ISBN、标题、版本号、版权)”; } //插入 如果(选项==4) { query=“插入授权BN(AuthorID,ISBN)”+ “价值观(authorID,ISBN)”; } 如果(选项==5) { query=“从Authors中选择authord、FirstName、LastName”; } 如果(选项==6) { query=“从标题中选择ISBN、标题、编辑编号、版权”; } } 私有void运行查询(String queryToRun)引发异常,SQLException { 字符串sqlMessage=null; //执行查询并获得结果 试一试{ System.out.println(“创建语句…”); statement=connection.createStatement(); resultSet=statement.executeQuery(queryRun); } 捕获(SQLE异常) { 如果(e!=null) sqlMessage=e.getMessage(); System.out.println(“SQL错误消息1:+sqlMessage”); 返回; } 试一试{ //处理查询结果 ResultSetMetaData元数据=resultSet.getMetaData(); numberOfColumns=metaData.getColumnCount(); System.out.println(“图书数据库表:\n”); //显示行集标题 对于(int i=1;i
,下面是一个如何使用JDBC创建参数化语句的示例:Java 设置FirstName=FirstName,LastName=LastName+ “其中AuthorID=AuthorID)”; } //插入标题 如果(选项==3) { query=“插入标题(ISBN、标题、编辑编号、版权)”+ “价值(ISBN、标题、版本号、版权)”; } //插入 如果(选项==4) { query=“插入授权BN(AuthorID,ISBN)”+ “价值观(authorID,ISBN)”; } 如果(选项==5) { query=“从Authors中选择authord、FirstName、LastName”; } 如果(选项==6) { query=“从标题中选择ISBN、标题、编辑编号、版权”; } } 私有void运行查询(String queryToRun)引发异常,SQLException { 字符串sqlMessage=null; //执行查询并获得结果 试一试{ System.out.println(“创建语句…”); statement=connection.createStatement(); resultSet=statement.executeQuery(queryRun); } 捕获(SQLE异常) { 如果(e!=null) sqlMessage=e.getMessage(); System.out.println(“SQL错误消息1:+sqlMessage”); 返回; } 试一试{ //处理查询结果 ResultSetMetaData元数据=resultSet.getMetaData(); numberOfColumns=metaData.getColumnCount(); System.out.println(“图书数据库表:\n”); //显示行集标题 对于(int i=1;i,java,sql,oracle,jdbc,Java,Sql,Oracle,Jdbc,,下面是一个如何使用JDBC创建参数化语句的示例: // Use the try-with-resources statement to properly manage resources in Java try (PreparedStatement stmt = connection.prepareStatement( // Use ? parameter markers in prepared statements "INSERT INTO AuthorISBN (Auth
// Use the try-with-resources statement to properly manage resources in Java
try (PreparedStatement stmt = connection.prepareStatement(
// Use ? parameter markers in prepared statements
"INSERT INTO AuthorISBN (AuthorID, ISBN) VALUES (?, ?)"
)) {
// Prior to executing the statement, you have to bind actual values to the parameters
stmt.setInt(1, authorID);
stmt.setInt(2, ISBN);
// Again, use try-with-resources
try (ResultSet rs = stmt.executeQuery()) {
// Now, do your thing.
}
}
在查询中嵌入用户输入时,不要使用“静态语句”(Connection.createStatement()
),原因如下:
- (可能不适用于您的简单应用程序)
insert
和update
查询没有任何替换占位符。您认为在作者(FirstName,LastName)值(FirstName,LastName)中插入什么内容
将用于值?您的查询字符串中也缺少一些空格。请查看有关使用JDBC和参数化查询的教程以获取帮助。太好了,谢谢。您有链接吗?我刚刚在谷歌上搜索了“JDBC和参数化查询”我得到的想法是,我需要使用准备好的语句。这似乎是正确的方向吗?如果你用谷歌搜索“Oracle JDBC教程”,会发生什么?这很好:。除了使用SELECT,我对如何使用resultSet方法不太清楚,但我会继续努力
import java.sql.*;
import java.util.Scanner;
public class ConnectAndRunQueries {
private final static String dbURL = "jdbc:oracle:thin:@coisor.austincc.edu:1527:CSOR";
private final static String dbUser = "user";
private final static String dbPasswd = "password";
Connection connection = null;
Statement statement = null;
public int choice = 0;
public String firstName;
public String lastName;
public int authorID;
public int ISBN;
public String title;
public int editionNumber;
public String copyright;
public Boolean quit = false;
public ResultSet resultSet = null;
public Boolean weAreOkay = false;
public String query = null;
public int numberOfColumns = 0;
public static void main(String args[]) throws Exception
{
try {
// Load the driver class
Class.forName("oracle.jdbc.OracleDriver");
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
return;
}
catch(Exception e) {
System.out.println("Failed to load SQL driver." + e);
return;
}
ConnectAndRunQueries myObject = new ConnectAndRunQueries();
myObject.driver();
}
public void driver() throws Exception
{
System.out.println("\nConnecting to the database...");
testConnectToDb();
getInput();
while (!quit)
{
createQueries();
System.out.println("Running query:");
runQueries(query);
if (choice == 5)
{
displayQueries();
choice = 5;
createQueries();
runQueries(query);
}
getInput();
}
System.out.println("Closing the Database Connection...");
closeDBConnection();
}
private boolean testConnectToDb()
{
boolean rtnCode = false;
try {
connection = DriverManager.getConnection(dbURL, dbUser, dbPasswd);
if(connection != null)
{
rtnCode = true;
}
}
catch (SQLException e)
{
e.printStackTrace();
}
if (rtnCode)
System.out.println("The database connection was successful");
else
System.out.println("The database connection was Not successful");
return rtnCode;
}
// Close the Database connection.
private void closeDBConnection() throws Exception, SQLException
{
try
{
if (statement != null)
statement.close();
if (connection != null)
connection.close(); // Close the database connection
}
catch (SQLException e)
{
e.printStackTrace();
}
}
private void getInput()
{
Scanner input = new Scanner(System.in);
Scanner scanner = new Scanner(System.in);
System.out.println("Menu");
System.out.println("Choose from the following:");
System.out.println(" 1. Add a new author");
System.out.println(" 2. Edit an existing author");
System.out.println(" 3. Add a new Title");
System.out.println(" 4. Add a new Author/Title combination");
System.out.println(" 5. Print databases");
System.out.println(" 6. Exit");
System.out.println(" Make selection : ");
Integer input1 = scanner.nextInt();
//scanner.close();
if (input1 == 1)
{
System.out.println(" Enter author first name: ");
firstName = input.nextLine();
System.out.println(" Enter author last name: ");
lastName = input.nextLine();
choice = 1;
input.close();
}
if (input1 == 2)
{
System.out.println(" Enter authorID: ");
authorID = input.nextInt();
System.out.println(" Enter author first name: ");
firstName = input.nextLine();
input.nextLine();
System.out.println(" Enter author last name: ");
lastName = input.nextLine();
choice = 2;
input.close();
}
if (input1 == 3)
{
System.out.println(" Enter ISBN number: ");
ISBN = input.nextInt();
System.out.println(" Enter Title: ");
title = input.nextLine();
input.nextLine();
System.out.println(" Enter Edition Number: ");
editionNumber = input.nextInt();
System.out.println(" Enter Copyright year: ");
copyright = scanner.nextLine();
input.nextLine();
System.out.println(" Enter authorID: ");
authorID = scanner.nextInt();
choice = 3;
input.close();
}
if (input1 == 4)
{
System.out.println(" Enter authorID: ");
authorID = scanner.nextInt();
System.out.println(" Enter ISBN number: ");
ISBN = scanner.nextInt();
choice = 4;
input.close();
}
if (input1 == 5)
{
choice = 5;
}
if (input1 == 6)
{
quit = true;
}
return;
}
private void createQueries()
{
//INSERT INTO Authors
if (choice == 1)
{
query = "INSERT INTO Authors (FirstName, LastName)" + "VALUES (firstName, lastName) ";
}
//UPDATE authors
if (choice == 2)
{
query = "UPDATE Authors " +
" SET FirstName = firstName, LastName = lastName " +
" WHERE AuthorID = authorID) ";
}
//INSERT title
if (choice == 3)
{
query = "INSERT INTO Titles (ISBN, Title, EditionNumber, Copyright)" +
" VALUES (ISBN, title, editionNumber, copyright) ";
}
//INSERT INTO AuthorISBN
if (choice == 4)
{
query = "INSERT INTO AuthorISBN (AuthorID, ISBN)" +
" VALUES (authorID, ISBN) ";
}
if (choice == 5)
{
query = "SELECT AuthorID, FirstName, LastName FROM Authors";
}
if (choice == 6)
{
query = "SELECT ISBN, Title, EditionNumber, Copyright FROM Titles";
}
}
private void runQueries(String queryToRun)throws Exception, SQLException
{
String sqlMessage = null;
// Execute the query and get our result
try {
System.out.println("Creating statement...");
statement = connection.createStatement();
resultSet = statement.executeQuery(queryToRun);
}
catch (SQLException e)
{
if (e != null)
sqlMessage = e.getMessage();
System.out.println("SQL Error Message 1: " + sqlMessage);
return;
}
try {
// process query results
ResultSetMetaData metaData = resultSet.getMetaData();
numberOfColumns = metaData.getColumnCount();
System.out.println("Table of Books Database:\n");
// display row set header
for (int i = 1; i <= numberOfColumns; i++)
System.out.printf("%-8s\t", metaData.getColumnName(i));
System.out.println();
// display each row
while (resultSet.next())
{
for (int i = 1; i <= numberOfColumns; i++)
System.out.printf("%-8s\t", resultSet.getObject(i));
System.out.println();
}
}
catch (SQLException e)
{
weAreOkay = false;
if (e != null)
sqlMessage = e.getMessage();
System.out.println("SQL Error Message 2: " + sqlMessage);
e.printStackTrace();
}
}
public void displayQueries() throws Exception, SQLException
{
String sqlMessage = null;
ResultSetMetaData metaData;
try
{
metaData = resultSet.getMetaData();
int numberOfColumns = metaData.getColumnCount();
System.out.println("");
for (int i = 1; i <= numberOfColumns; i++)
System.out.printf("%-16s\t", metaData.getColumnName(i),"%n");
while (resultSet.next() && weAreOkay)
{
for (int i = 1; i <= numberOfColumns; i++)
System.out.printf("%-16s\t", resultSet.getObject(i));
System.out.println();
}
}
catch (SQLException e)
{
weAreOkay = false;
if (e != null) sqlMessage = e.getMessage();
System.out.println("SQL Error Message 2: " + sqlMessage);
e.printStackTrace();
}
}
}
// Use the try-with-resources statement to properly manage resources in Java
try (PreparedStatement stmt = connection.prepareStatement(
// Use ? parameter markers in prepared statements
"INSERT INTO AuthorISBN (AuthorID, ISBN) VALUES (?, ?)"
)) {
// Prior to executing the statement, you have to bind actual values to the parameters
stmt.setInt(1, authorID);
stmt.setInt(2, ISBN);
// Again, use try-with-resources
try (ResultSet rs = stmt.executeQuery()) {
// Now, do your thing.
}
}