我想将上传的文件(如照片,视频,PDF,Excel ....)存储在数据库中。当我上传文件时,应该存储的数据是文件路径,类型和时间戳。我的数据库列是id,file,type,timestamp。
答案 0 :(得分:0)
long long
答案 1 :(得分:0)
我想你问如何使用vanilla java(no hibernate)将信息插入MySQL数据库。
Vanilla Java示例(alvinalexander.com):
import java.sql.*;
import java.util.Calendar;
/**
* A Java MySQL PreparedStatement INSERT example.
* Demonstrates the use of a SQL INSERT statement against a
* MySQL database, called from a Java program, using a
* Java PreparedStatement.
*
* Created by Alvin Alexander, http://alvinalexander.com
*/
public class JavaMysqlPreparedStatementInsertExample
{
public static void main(String[] args)
{
insertDataBase("uploads/demo","pdf");
}
public static insertDataBase(String filePath,String extension) {
try
{
// create a mysql database connection
String myDriver = "com.mysql.jdbc.Driver";
String myUrl = "jdbc:mysql://localhost/test";
Class.forName(myDriver);
Connection conn = DriverManager.getConnection(myUrl, "root", "");
// create a sql date object so we can use it in our INSERT statement
Calendar calendar = Calendar.getInstance();
java.sql.Date timeStamp = new java.sql.Date(calendar.getTime().getTime());
// the mysql insert statement
String query = " insert into upload (file, type, timestamp)"
+ " values (?, ?, ?)";
// create the mysql insert preparedstatement
PreparedStatement preparedStmt = conn.prepareStatement(query);
preparedStmt.setString (1, filePath);
preparedStmt.setString (2, extension);
preparedStmt.setDate (3, timeStamp);
// execute the preparedstatement
preparedStmt.execute();
conn.close();
}
catch (Exception e)
{
System.err.println("Got an exception!");
System.err.println(e.getMessage());
}
}
}
在运行代码之前,您需要使用maven或download将mysql驱动程序添加到类路径中。 希望它能帮到你!