How to Create a Database with Code
Methods for creating databases can vary depending on the programming language and database management system being used. Below are examples of code for some common programming languages and database management systems.
Create a database using Python and SQLite.
import sqlite3
# 连接到数据库(如果不存在则创建)
conn = sqlite3.connect('database.db')
# 创建游标对象
cursor = conn.cursor()
# 创建表
cursor.execute('''CREATE TABLE IF NOT EXISTS users
(id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT,
age INTEGER,
email TEXT)''')
# 提交更改并关闭连接
conn.commit()
conn.close()
Creating a database using Java and MySQL.
import java.sql.*;
public class Main {
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try {
// 注册 JDBC 驱动
Class.forName("com.mysql.jdbc.Driver");
// 打开连接
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/database", "username", "password");
// 执行查询
stmt = conn.createStatement();
String sql = "CREATE TABLE IF NOT EXISTS users " +
"(id INT PRIMARY KEY AUTO_INCREMENT, " +
"name VARCHAR(255), " +
"age INT, " +
"email VARCHAR(255))";
stmt.executeUpdate(sql);
System.out.println("Database created successfully.");
} catch (SQLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if(stmt != null)
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
if(conn != null)
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
Please note that the code in the above example is for demonstration purposes only. In actual projects, error handling and security considerations should be implemented as needed.