你如何使用jdbc預製這種類型的動作?JDBC如何預渲染'。 somesqlfile.sql「?
String x = ("\\. /home/user/Desktop/dbfile.sql");
Class.forName(Database.JDBC_DRIVER);
Connection conn = (Connection) DriverManager.getConnection(
Database.DB_URL + "localhost" + "/" + "mydatabase", "root", "");
Statement stmt = (Statement) conn.createStatement();
stmt.execute(x);
結果:異常線程 「main」 com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException:您的SQL語法錯誤;檢查與你的MySQL服務器版本相對應的手冊,在''附近'使用正確的 語法'。
我已經試過這
public static void main(String[] args) throws Exception
{
String x = readFileAsString("/home/user/Desktop/myDB.sql");
Class.forName(Database.JDBC_DRIVER);
Connection conn = (Connection) DriverManager.getConnection(
Database.DB_URL + "localhost" + "/" + "mydb", "root", "");
Statement stmt = (Statement) conn.createStatement();
System.out.println(x);
stmt.execute(x);
}
private static String readFileAsString(String filePath) throws Exception
{
byte[] buffer = new byte[(int) new File(filePath).length()];
BufferedInputStream f = null;
try
{
f = new BufferedInputStream(new FileInputStream(filePath));
f.read(buffer);
}
finally
{
if (f != null)
try
{
f.close();
}
catch (IOException ignored)
{
}
}
return new String(buffer);
}
結果
Exception in thread "main" com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'SET @[email protected]@CHARACTER_SET_RESULTS */;
我的文件看起來像
-- MySQL dump 10.13 Distrib 5.5.21, for Linux (x86_64)
--
-- Host: localhost Database: DOG
-- ------------------------------------------------------
-- Server version 5.5.21
/*!40101 SET @[email protected]@CHARACTER_SET_CLIENT */;
/*!40101 SET @[email protected]@CHARACTER_SET_RESULTS */;
/*!40101 SET @[email protected]@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
/*!40103 SET @[email protected]@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @[email protected]@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @[email protected]@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @[email protected]@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @[email protected]@SQL_NOTES, SQL_NOTES=0 */;
--
-- Table structure for table `DOG`
--
DROP TABLE IF EXISTS `DOG`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `DOG` (
`DOG_ID` mediumint(9) NOT NULL,
`OWNER_ID` mediumint(9) NOT NULL,
PRIMARY KEY (`DOG_ID`,`OWNER_ID`),
KEY `CHANNEL_FK1` (`OWN_ID`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
請教我如何。我幾天來一直在尋找這個答案! – stackoverflow 2012-04-13 16:16:21
如果您的語句不在一行(幾乎總是這種情況),則sqeeze回車在您的字符串中並按「;」分隔。 。這樣,你可以得到一系列可以在循環中執行的語句! – 2012-04-13 16:24:04