I have a string like these "Marko's place" "boulevard "Arequipa"" strings that containing single or double quotes, in Java using regular expressions how get that the previous strings get like this "Marko\s place" "boulevard \"Arequipa\"" I am no have experience with regex, thank for any answer
OK, I am reading records from a mysql table and constructing the insert sql to pass this information to a sqlite table
Statement qryMySQL= cnMySql.createStatement();
ResultSet rs = qryMySQL.executeQuery("select * from tblclientes ");
Statement qrySQLite = cnSqLite.createStatement();
qrySQLite.addBatch("begin transaction");
qrySQLite.addBatch("CREATE TABLE 'tblclientes' ('_id' INTEGER,'Nombres' varchar(25) DEFAULT NULL,'Apellidos' varchar(25) DEFAULT NULL,'RazSocial' varchar(20) DEFAULT NULL,'Direccion' varchar(50) DEFAULT NULL,'Ciudad' varchar(15) DEFAULT 'Arequipa','Fono' varchar(12) DEFAULT NULL,'Fax' varchar(12) DEFAULT NULL,'Email' varchar(35) DEFAULT NULL,'Ruc' varchar(12) DEFAULT NULL,'latitud' decimal(20,14) DEFAULT NULL,'longitud' decimal(20,14) DEFAULT NULL,'ruta' varchar(10) DEFAULT NULL,'sincro' CHAR(10),'copiar' BOOL DEFAULT 1)");
while (rs.next())
{
//System.out.println (rs.getInt(1) + " " + rs.getString (2) );
sql = "INSERT INTO tblclientes(_id,nombres,apellidos) " +
"VALUES("+rs.getInt("id")+", \""+rs.getString("nombres")+"\",\""+rs.getString("apellidos")+"\")";
qrySQLite.addBatch(sql);
// System.out.println (sql);
}
qrySQLite.addBatch("end transaction");
qrySQLite.executeBatch();
but some fields in the mysql table have the characters " and ' that causes error in sql insert sentence then I Need this
<Marko's place> ===> <Marko\'s place>
<boulevard "Arequipa"> ====> <boulevard \"Arequipa">
so the result must be add the \ before the " or '
I would probably use the Apache Commons StringEscapeUtils it catches a lot more corner cases then you have in your question -
StringEscapeUtils.escapeJava(str);
Otherwise, you could just use string replace like this
String str = "\"Marko's place\"";
System.out.println(str.replace("'", "\\'").replace("\"", "\\\""));
Related
I used this code to have the user put the column name in the database / text =
"create table oop('"+id+"' varchar(30) not null,'"+name+"' varchar(20) not null,'"+lastname+"' varchar(20) notnull,'"+salary+"' varchar(30) not null) " ;
is error
What is the correct code to make the user put the column names inside the table in Databases via SQL?
Just remove the single quotes around the column name: they stand for literal strings, not for identifiers:
"create table oop(" + id + " varchar(30) not null," + name + " varchar(20) not null," + lastname + " varchar(20) notnull, " + salary + " varchar(30) not null)" ;
On the other hand, if your identifiers contain special characters, then you need to quote them: for this, use the relevant quoting character for your database: MySQL wants backticks, SQL Server has square brackets, ([]), Postgres and Oracle use the double quote "".
Make a PROCEDURE like:
CREATE PROCEDURE sproc_BuildTable
#TableName NVARCHAR(128)
,#Column1Name NVARCHAR(32)
,#Column1DataType NVARCHAR(32)
,#Column1Nullable NVARCHAR(32)
AS
DECLARE #SQLString NVARCHAR(MAX)
SET #SQString = 'CREATE TABLE '+#TableName + '( '+#Column1Name+' '+#Column1DataType +' '+#Column1Nullable +') ON PRIMARY '
EXEC (#SQLString)
GO
This stored procedure can be executed like this:
sproc_BuildTable 'Customers','CustomerName','VARCHAR(32)','NOT NULL'
Okay, so I just started JDBC with derby client and I'm kind of new with it.
I set column ID as primary key with int as it's data type. However, I'm not sure if I should include myStatement.setString(1, ?); because I thought it should Auto Increment but it looks like it's not doing it.
Here's my Grab file details:
create table "ADMIN1".STUDENTPERSONALDETAILS
(
ID INTEGER not null primary key,
STUDENTID VARCHAR(10) not null,
LASTNAME VARCHAR(50) not null,
FIRSTNAME VARCHAR(50) not null,
MIDDLENAME VARCHAR(50) not null,
PLACEOFBIRTH VARCHAR(200) not null,
DOB VARCHAR(50) not null,
GENDER VARCHAR(4) not null,
CIVILSTATUS VARCHAR(7) not null,
RELIGION VARCHAR(15) not null,
NATIONALITY VARCHAR(20) not null
)
How can I correct my PreparedStatement or My Table in such a way that adding of value for column ID will be automatic so that I can start setString(2, studentID) and avoid getting error about the number of columns not matching with what was supplied?
Here's my code:
addButton.addActionListener(new ActionListener () {
#Override
public void actionPerformed(ActionEvent e) {
try {
String myDbUrl = "jdbc:derby://localhost:1527/Enrollment"; //stores url to string
String userName = "admin1";
String Password = "admin1";
Connection myDBConnection = DriverManager.getConnection(myDbUrl, userName, Password);
String myQuery = "INSERT INTO STUDENTPERSONALDETAILS"
+ "(STUDENTID,LASTNAME,FIRSTNAME,MIDDLENAME,PLACEOFBIRTH,DOB,GENDER,CIVILSTATUS,RELIGION,NATIONALITY) "
+ "VALUES(?,?,?,?,?,?,?,?,?,?) ";
String adminissionNo ;
String studentID = tfStudentId.getText().toString();
String lastName = tfLastName.getText().toString();
String firstName = tfFirstName.getText().toString();
String middleName = tfMiddleName.getText().toString();
String placeOfBirth = tfPob.getText().toString();
String dateOfBirth = listDOB.getSelectedItem().toString();
String gender = listGender.getSelectedItem().toString();
String civilStatus = listCivilStatus.getSelectedItem().toString();
String religion = listReligion.getSelectedItem().toString();
String nationality = listNationality.getSelectedItem().toString();
PreparedStatement myStatement = myDBConnection.prepareStatement(myQuery);
myStatement.setString(2, lastName);
myStatement.setString(3, firstName);
myStatement.setString(4, middleName);
myStatement.setString(5, placeOfBirth);
myStatement.setString(6, dateOfBirth);
myStatement.setString(7, gender);
myStatement.setString(8, civilStatus);
myStatement.setString(9, religion);
myStatement.setString(10, nationality);
boolean insertResult = myStatement.execute();
if(insertResult == true)
JOptionPane.showMessageDialog(null, "Successfully Added Information");
else
JOptionPane.showMessageDialog(null, "Encountered an error while inserting data");
}
catch(SQLException ex) {
JOptionPane.showMessageDialog(null, ex.toString());
}
}
});
Is it necessary to include myStatement.setString(1, integervaluehere) for Primary Keys? Isn't it supposed to autoincrement?
I'd appreciate any explanation because I just started learning the basics of PreparedStatements recently.
I tried counting the columns and tried 10 and 11 lines of myStatement.setString(), but still can't get it to insert data because of mismatch.
Thanks in advance.
You need to mention 'auto increment' explicitly.
Or you can write your own java code to track the Id for each table and whenever you ask the method to give the ID it will return lastID + 1.
But, I think now you can go with auto_increment option.
If you want it to autoincrement you need to say so in the column definition, and you haven't.
I don't know what 'default 1' in your title is supposed to mean, as you haven't mentioned it in your question, but you can't have a default value and autoincrement. It doesn't make sense.
I don't know what 'store seed 1' means either, in your edit.
When you have a column with a default value you want to rely on, or autoincrement, you don't mention it at all in the INSERT statement, so there is no positional argument to set.
First, set the primary identifier column to autoincrement. Since your query already excludes the primary key, you then only have to change the PreparedStatement indexes to match the number of parameters in your query starting from one.
Since you have 10 columns in addition to the primary ID column, your PreparedStatement might look something like the following:
PreparedStatement myStatement = myDBConnection.prepareStatement(myQuery);
myStatement.setString(1, studentId);
myStatement.setString(2, lastName);
myStatement.setString(3, firstName);
myStatement.setString(4, middleName);
myStatement.setString(5, placeOfBirth);
myStatement.setString(6, dateOfBirth);
myStatement.setString(7, gender);
myStatement.setString(8, civilStatus);
myStatement.setString(9, religion);
myStatement.setString(10, nationality);
Note that you do not need to have the instruction, myStatement.setInt(1, primaryId);, once you have changed the primary key in your table to auto-increment. However, if you elect to keep the primary key as non-autoincrementing, then you must explicitly specify the primary key value and provide a parameter in your query to insert that data.
If you're using MySQL Workbench, which if you're not, I highly recommend because it just works. You have to choose Auto-Increment as a characteristic of that column. If you want your column to auto increment, when creating columns in your database, check the option Auto-Increment, sometimes written as AI.
I'm modifying someone else's Java code, learning Java as I go. :-). I'm writing hsqldb TEXT files, and I would like the final files to have a 'heading' row, so that they can be more easily understood as plain text. hsqldb has a switch 'ignore_first=true' for reading such files, but I can't find a way to write the line in. It may not exist, but there is a tantalizing reference to SOURCE HEADER in the documentation. Does anyone know how to use it?
Here is a simplified sample of what I have tried:
String createtextTable =
"CREATE TEXT TABLE MolSet (" +
" id INT NOT NULL IDENTITY," +
" filename VARCHAR(300)," +
" expSolFilename VARCHAR(300)," +
" variance DOUBLE" + ");" ;
String headingsTable = "id,filename,expSolFilename, variance";
try
{
stmt = conn.createStatement();
stmt.execute(createtextTable);
setTableStmt = "SET TABLE " + “MolSet” + " SOURCE " +
'"' + TABLES[0] + ".csv;ignore_first=true" + '"';
stmt.execute(setTableStmt);
headingStmt = "SET TABLE " + “MolSet” + " SOURCE HEADER " +
'"' + headingsTable + '"';
stmt.execute(headingStmt);
}
catch( SQLException sqle )
{
return false;
}
return true;
}
this gives sql error:
Invalid TEXT table source string in statement [SET TABLE MolSet SOURCE HEADER]
I hope you can help, even if it is to confirm it is impossible. Thanks,
Jocelyn
The source and source header strings must be enclosed in single quotes:
SET TABLE MolSet SOURCE HEADER 'id,filename,expSolFilename,variance'
You have used double quotes instead.
Edit: The answer is for the latest version. Older versions since 1.8.x support this, but may require double quotes. The number of columns in the header and table must match. Alternatively, you can edit the text source while the database is offline and add the headers yourself.
This SQL file works for making CSV text files from a table and also sets field headers. It is specific for HSQLDB (version 1.8.1.3).
Website for database DL and docs is HSQLDB.ORG
I hope it helps.
-- ========================
-- MAKE TABLE TEXT_TABLE_01
-- ========================
DROP TABLE TEXT_TABLE_01 IF EXISTS;
CREATE TEXT TABLE TEXT_TABLE_01
( ID_NUMBER INTEGER
, FIRST_NAME VARCHAR(30)
, LAST_NAME VARCHAR(30)
, DEAR_ VARCHAR(50)
)
;
SET TABLE TEXT_TABLE_01 SOURCE "TEXT_TABLE_01.TXT;ignore_first=true;fs=:";
SET TABLE TEXT_TABLE_01 SOURCE HEADER "ID_NUMBER:FIRST_NAME:LAST_NAME:DEAR_";
INSERT INTO TEXT_TABLE_01
( ID_NUMBER, FIRST_NAME, LAST_NAME, DEAR_ )
SELECT
ID_NUMBER, FIRST_NAME, SURNAME, DEAR_
FROM
TMP_NON_PERSONAL
;
SELECT * FROM TEXT_TABLE_01;
SET TABLE TEXT_TABLE_01 SOURCE OFF;
-- DELETE ALL TEXT FILES WHEN FINISHED ... OR BEFORE STARTING ...
Hello i am using prepared statement to insert the values into mysql.
I am facing an issue in an string which is inserting as "c2a054656e6e6973c2a0" for value " Tennis " and i tried to use trim to trim the whitespace in front of the "Tennis" it did not work .From this question Why trim is not working? i tried using the solution poNumber.replace(String.valueOf((char) 160), " ").trim(); and it worked. can any one give solution for this?
SAMPLE CODE
CREATE TABLE `news1` (
`article_id` int(11) NOT NULL AUTO_INCREMENT,
`article_title` varchar(500) COLLATE utf8_bin NOT NULL,
`article_subcategory` varchar(255) COLLATE utf8_bin DEFAULT NULL,
PRIMARY KEY (`article_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin AUTO_INCREMENT=22 ;
//Sample category will be "Home » Tennis"
String category = item.getArticle_category();
String categoryArray[] = category.split("»");
preparedStatement = connect
.prepareStatement("INSERT INTO news1 VALUES(default,?,?)");
System.out.println(categoryArray[2].replace(String.valueOf((char) 160), " ")
.trim());
preparedStatement.setString(1, item.getArticle_title());
preparedStatement.setString(2, categoryArray[2]);
you are doing this categoryArray[2].replace(String.valueOf((char) 160), " ") .trim() in sys out but you do preparedStatement.setString(2, categoryArray[2]); in your statement
String temp = categoryArray[2].replace(String.valueOf((char) 160), " ") .trim();
System.out.println(temp);
and use temp in
preparedStatement.setString(2, temp);
Oracle keeps giving me an invalid identifier error when I clearly have identified the variable.
//get parameters from the request
String custID=request.getParameter("cust_ID");
String saleID=request.getParameter("sale_ID");
String firstName=request.getParameter("first_Name");
String mInitial=request.getParameter("mI");
String lastName=request.getParameter("last_Name");
String streetName=request.getParameter("street");
String city=request.getParameter("city");
String state=request.getParameter("state");
String zipCode=request.getParameter("zip_Code");
String DOB2=request.getParameter("DOB");
String agentID=request.getParameter("agent_ID");
String homePhone=request.getParameter("home_Phone");
String cellPhone=request.getParameter("cell_Phone");
String profession=request.getParameter("profession");
String employer=request.getParameter("employer");
String referrer=request.getParameter("referrer");
query =
"UPDATE customer"
+ " SET customer.cust_ID=custID, customer.sale_ID=saleID, customer.first_Name=firstName, customer.mI=mInitial, customer.last_Name=lastName, customer.street_Name=streetName, customer.city=city, customer.state=state, customer.zip_Code=zipCode,customer. DOB=DOB2, customer.agent_ID=agentID, customer.home_Phone=homePhone, customer.cell_Phone=cellPhone, customer.profession=profession, customer.employer=employer, customer.referrer=referrer"
+ " WHERE customer.cust_ID=custID " ;
preparedStatement = conn.prepareStatement(query);
preparedStatement.executeUpdate();
SQL TABLE
CREATE TABLE customer
(cust_ID NUMBER NOT NULL,
sale_ID NUMBER NOT NULL,
first_NameVARCHAR2(30) NOT NULL,
mI VARCHAR2(2) ,
last_Name VARCHAR2(50) NOT NULL,
street_Name VARCHAR2(50) ,
city VARCHAR2(30) NOT NULL,
state VARCHAR2(50) NOT NULL,
zip_Code VARCHAR2(5) NOT NULL,
DOB DATE ,
agent_ID NUMBER ,
home_Phone VARCHAR2(12) UNIQUE,
cell_Phone VARCHAR2(12) UNIQUE,
profession VARCHAR2(30) ,
employer VARCHAR2(30) ,
referrer VARCHAR2(30)
);
Your code is not doing what you think it is. Look at this:
query =
"UPDATE customer"
+ " SET customer.cust_ID=custID, customer.sale_ID=saleID, customer.first_Name=firstName, customer.mI=mInitial, customer.last_Name=lastName, customer.street_Name=streetName, customer.city=city, customer.state=state, customer.zip_Code=zipCode,customer. DOB=DOB2, customer.agent_ID=agentID, customer.home_Phone=homePhone, customer.cell_Phone=cellPhone, customer.profession=profession, customer.employer=employer, customer.referrer=referrer"
+ " WHERE customer.cust_ID=custID "
The content of query at this point is exactly what will be sent to the database. JSP will not magically fill in custID, saleID (etc...) for you before sending the query to the database. Because of this, Oracle has no sweet clue what custID is (it certainly isn't the name of some other column in the customer table). Hence, you receive the invalid identifier error.
I think you were trying to do this:
query =
"UPDATE customer"
+ " SET customer.cust_ID=" + custID + ", customer.sale_ID=" + saleID + ...
Like duffymo mentioned, this is asking for serious SQL-injection trouble (just think of the values that the client could submit in order to hijack your SQL via the custID field). The better way is to use parameters on a PreparedStatement:
query =
"UPDATE customer"
+ " SET customer.cust_ID=?, customer.sale_ID=? ...";
PreparedStatement statement = conn.prepareStatement(query);
statement.setString(1, custID);
statement.setString(2, saleID);
statement.executeUpdate();
I'd recommend not using scriplets in your JSPs. Learn JSTL as quickly as you can.
The answer seems pretty obvious: your parameters are all Strings, but the Oracle schema has some Data and Number types. You've got to convert to the correct type when you INSERT.
This code is begging for a SQL injection attack. You don't do any binding or validation before you INSERT. You couldn't possibly be less secure than this. I hope you don't intend to use this site for anything on the web.
A better approach would take the scriptlet code out of the JSP, use only JSTL to write it, and introduce a servlet and some other layers to help with binding, validation, security, etc.
I think in the sql query you have entered space in between customer,DOB.
customer. DOB=DOB2