kotlin sql查字段长度
时间: 2023-09-22 16:06:15 浏览: 146
在 Kotlin 中,您可以使用以下代码来查询 SQL 表中的字段长度:
```kotlin
import java.sql.Connection
import java.sql.DriverManager
import java.sql.SQLException
fun main() {
// 建立数据库连接
val url = "jdbc:mysql://localhost:3306/database_name"
val username = "your_username"
val password = "your_password"
try {
val connection: Connection = DriverManager.getConnection(url, username, password)
// 查询字段长度
val columnName = "column_name"
val tableName = "table_name"
val query = "SELECT CHARACTER_MAXIMUM_LENGTH FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = ? AND COLUMN_NAME = ?"
val statement = connection.prepareStatement(query)
statement.setString(1, tableName)
statement.setString(2, columnName)
val resultSet = statement.executeQuery()
if (resultSet.next()) {
val maxLength = resultSet.getInt(1)
println("Max length of $columnName in $tableName is $maxLength")
} else {
println("Column $columnName not found in table $tableName")
}
// 关闭连接
resultSet.close()
statement.close()
connection.close()
} catch (e: SQLException) {
e.printStackTrace()
}
}
```
请注意替换代码中的 `database_name`、`your_username`、`your_password`、`column_name` 和 `table_name` 为您实际使用的值。
阅读全文