Вопрос

When i create a table with SQL using Java and JDBC i get get undesired whitespace.

CREATE TABLE Customers(name char(15), lname char(15), adress char(15)) 

When i put something in the columns that consists of less characters than the column allows, whitespace is added to the input.

INSERT INTO Customers VALUES ('John', 'Doe', 'Somestreet')

So 'John' becomes 'John ' with eleven whitespace characters. This is a big problem when it comes to further statements. From what i know you can use LIKE but i want to prevent issues with entries like 'John-Paul'. So i would like to know if you can help me to fix the problem.

My Java code would be something like this:

PreparedStatement prep = con.prepareStatement("UPDATE Customers SET lname=? WHERE name=?");
prep.setString(1, "Example");
prep.setString(2, "John"); // this doesn't work
prep.executeUpdate();
Это было полезно?

Решение

This has nothing to do with Java: database type char(length) is used to specify fixed-length strings, which are padded with whitespace on retrieval to the desired length when the data stored in them has fewer characters than is specified at the definition.

To address this problem, use a data type that is appropriate for variable-length strings, i.e. a varchar, nvarchar, or text:

CREATE TABLE Customers(
    name   nvarchar(15)
,   lname  nvarchar(15)
,   adress nvarchar(15)
) 

Другие советы

The Char data type is fixed length so if you say 15 it will alwasy be 15. If you want "strings you can trim" Use VarChar. You can still make max of 15, but the actual length will be the length of the string inserted.

Use varchar(15) or nvarchar(15) instead of char because char data type is fixed length.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top