Quantcast
Channel: MySQL Forums - Connector/J, JDBC and Java
Viewing all 884 articles
Browse latest View live

Accessing MySQL database through EJB and JPA entity and Assigning Security Control (no replies)

$
0
0
Dear All. Good day! I trust this catches you well.

I am developing an EJB application, a project here in my company. Because this is the very first time we work with EJBs I can't help but have 2 important questions, about which your kind assistance is highly appreciated.

(1) How can I insert data in database tables by calling the EJB from a Java SE client main method? By way of test I wrote a simple EJB and Java code. Here is the snippet:

@Stateless
public class insertRecordBean implements insertRecordRemote {


@PersistenceContext(unitName = "EJBDB-ejbPU")
private EntityManager em;

@TransactionAttribute(TransactionAttributeType.REQUIRED)
public void createTest(int id, String name) {

em.getTransaction().begin();
Testejb ts = new Testejb();
ts.setTId(id);
ts.setNome(name);
em.persist(ts);

and Java client main method:

public class Main {
@EJB
private static insertRecordRemote insertRecordBean;

@Resource
static UserTransaction ut;

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
System.out.println("Establishing connection to the bean...");
try{


InitialContext initialContext = new InitialContext();
insertRecordBean = (insertRecordRemote) initialContext.lookup
("server.insertRecordRemote");

ut.begin();

int id = 2;
String nome = "Flavia";

insertRecordBean.createTest(id, nome);
ut.commit();

// End of code snippets

A call similar to the above results in a simple EJB that does not access mysql db. What is missing,please?


(2) Each Java client will access some tables on the mysql db, with some privileges. If they were accessing the database from, say, mysql command-line shell they would have to enter username and password. How can I do a similar authentication in the java client main method? so that a user enters his credentials before doing any operations?

Looking forward to hear from you,
Thanks a million,
Victor

One specific Query doesn't run (1 reply)

$
0
0
Hi!

I have an issue running a group of querys on my app, but it really makes me headache that one specific query doesn't run. Here a brief explanation.

I'm converting Excel sheets into mysql tables, here everithing is allright.
then I declare a variable called "fecha", I use this variable several times in different querys and everything goes cool. but one specific query I'm sure is not working, worst there is no error message.

Here part of the code.

st.executeUpdate("UPDATE terminales_temporal a inner join (SELECT e.estatus, e.terminal,DATEDIFF('"+fecha+"',t.fecha_alta) FA FROM terminales_temporal t INNER JOIN estatus_terminales e ON t.terminal=e.terminal WHERE t.con_mov IS NULL AND e.mes=IF(t.mes=1,t.mes+11,t.mes-1)) b ON a.terminal = b.terminal SET a.estatus=1, a.descripcion_estatus = 'Sin Start' WHERE b.estatus = 1 AND FA >=0;");
st.executeUpdate("UPDATE terminales_temporal a inner join (SELECT e.estatus, e.terminal,DATEDIFF('"+fecha+"',t.fecha_alta) FROM terminales_temporal t INNER JOIN estatus_terminales e ON t.terminal=e.terminal WHERE t.con_mov IS NULL AND e.mes=IF(t.mes=1,t.mes+11,t.mes-1)) b ON a.terminal = b.terminal SET a.estatus=5, a.descripcion_estatus='Inicio de Inactividad' WHERE b.estatus in (2,3,4);");
st.executeUpdate("UPDATE terminales_temporal a inner join (SELECT e.estatus, e.terminal,DATEDIFF('"+fecha+"',t.fecha_alta) FROM terminales_temporal t INNER JOIN estatus_terminales e ON t.terminal=e.terminal WHERE t.con_mov IS NULL AND e.mes=IF(t.mes=1,t.mes+11,t.mes-1)) b ON a.terminal = b.terminal SET a.estatus=6, a.descripcion_estatus='Continua sin Operacion' where b.estatus in (5,6);");
==> this one is nor working st.executeUpdate("UPDATE terminales_temporal c inner join (SELECT d.terminal,DATEDIFF('"+fecha+"',d.fecha_alta) as FA FROM terminales_temporal as d WHERE d.con_mov IS NULL AND d.estatus IS NULL AND d.fecha_primer_mov IS NULL) as e on c.terminal = c.terminal SET c.estatus=1, c.descripcion_estatus = 'Sin Start' WHERE e.FA >=0;"); <====
st.executeUpdate("UPDATE terminales_temporal a inner join (SELECT terminal FROM terminales_temporal WHERE con_mov IS NULL AND fecha_cancel<>'0000-00-00') b on a.terminal = b.terminal SET estatus=7, descripcion_estatus='Cancelada';");

Any advice will be very apreciated, I don't know what else to show you.

Incorrect timestamp value (1 reply)

$
0
0
I have an application that's been in production several years. In various places I use Timestamp to record when various actions take place. This is more than just when a certain record is added or updated. Up to now I haven't had a bit of a problem with Timestamp. This week I started getting failures at any record that includes a Timestamp.

The error I am getting is:

[JDBCExceptionReporter] Data truncation: Incorrect timestamp value: '' for column 'last_labor_rpt_date' at row 1

Of course the column name can change but the results are the same. Currently on the database table the Timestamp field is saved as "YYYY-MM-DD HH:MM:SS". I am assuming from what I can see during debugging that for some reason Hibernate is now trying to include the decimal part of seconds, which for my purposes are totally unnecessary. I have tried requesting that Hibernate show the SQL at the insert/update. I get the SQL with the ? fields but I can't get it to show the actual data being inserted. So I can't be totally sure.

My log4j entries are:

<logger name="org.hibernate">
<level value="DEBUG" />
<appender-ref ref="CONSOLE"/>
</logger>

<logger name="org.hibernate.type">
<level value="TRACE" />
<appender-ref ref="CONSOLE"/>
</logger>

In the persistence.xml file I have:

<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.format_sql" value="true"/>
<property name="use_sql_comments" value="true"/>

My application is using Hibernate 3.3 with annotations. It is running on JBoss 4.3 and using MySQL 5.5.

The original code is:

private Timestamp lastLaborRptDate;
@Column(name = "last_labor_rpt_date", length=19)
public Timestamp getLastLaborRptDate() {
return this.lastLaborRptDate;
}
public void setLastLaborRptDate(Timestamp lastLaborRptDate) {
this.lastLaborRptDate = lastLaborRptDate;
}

It is still running fine on my production server. However, on my development server which basically duplicates the production environment, I am now getting these failures. This includes areas of the application that have been untouched.

I have tried several different things based on results of Google searches. Including changing the database field to DateTime with the same results.

I am stuck. How do I get past this?

Guide For Best Practice for Database Design (no replies)

$
0
0
Hi All,

According to my humble experience I have noticed the following related to database while creating an application :

1 . Most of the applications have a table called "user table"
2. Application should have audit or log table which contains all the actions done by the users ,
3. Delete operations should not really happened to keep in the integrity of the system but instead of that we have to keep a flag


my question what is the best practices to have a user table : is like


Method 1 :
user table



user_id Long
user_name vachar(50)
first_name vacarchar(50)
last_name vacarchar(50)
created_by Long
created_date date
updated_by Long
updated_date date
deleted tinyint
deleted_by Long
deleted_date date




or
Method 2

user_id Long
user_name vachar(50)
first_name vacarchar(50)
last_name vacarchar(50)
action_type tinyint COMMENT '1 create\n 2 update\n 3 delete\n'
action_date date



or Method 3
we will use the audit table which contains all the actions and the ids of the users ad the following

user table
user_id Long
user_name vachar(50)
first_name vacarchar(50)
last_name vacarchar(50)

action table
action_id Long
action_name varchar(500)

example for action_name 'create User' and 'Update User' and 'Delete User' ....etc


audit table
audit_id Long
user_id Long (foreign key of user_id in user table)
action_id Long (foreign key of action_id in action table)
description varchar(500)



or all above 3 methods are not the best approach .

Please guide me for the best database design


I am using Mysql and java

Java or other language affect to seo work (1 reply)

$
0
0
Hello,

i want to know that C++ or java or other programming language affects SEO works.

thanks

www.rudrra.com

SSB

foreign key issue-one to many (no replies)

$
0
0
Hi,

There is an issue related to foreign key. the error is as follows:

[JDBCExceptionReporter] SQL Error: 1452, SQLState: 23000
[JDBCExceptionReporter] Cannot add or update a child row: a foreign key constraint fails (`tms`.`groups`, CONSTRAINT `FK_groups` FOREIGN KEY (`GroupName`) REFERENCES `users` (`groupname`) ON DELETE CASCADE ON UPDATE CASCADE)

Thanks,
-Jeevan

About connection reuse (NEARLY MAD) (6 replies)

$
0
0
Hi everyone here,

I am using Ubuntu Desktop 12.04 and MySQL 5.6.

I put MySQL to work, created database, let my application connect to MySQL, and all things are going well, except that, I found my application cannot reuse the connection or set the currently used connection to idle for reuse, and then it continues allocating new connections in the connection pool until the number of the connections reaches the limits.
I have never met such situation before. I have ever deployed my application on Ubuntu Server 12.10 using the same configuration, it runs well with no connection problem.

I don't know why this happens, and how to fix this.
I need your help~~~

Thank you in advance!!

data makes it into DB as hex "3F3F3F3F" through connector/J driver (2 replies)


[replication driver] Expected behaviour when the master is down/unreachable (no replies)

$
0
0
Hello,

I am using connectorJ version 5.1.26 and replication driver. I use apache dbcp for the connection pool.

I was wondering what is the expected behaviour of the replication driver when the master is down/unreachable and new connections are being established?

I know if one of the slaves is down, there failover mechanism will pick another slave that is up. What is the expected behaviour when the master is down and the slave is up?

I looked at this bug report and did not find any conclusions yet: http://bugs.mysql.com/bug.php?id=50105

I would expect to be able to connect to the slave atleast so that read operations can go on.

Thanks
Vinay

Why does JDBC application logging SQL instructions in Apache Tomcat lists 545 repeatedly (1 reply)

$
0
0
I'm currently running a number of programs in batch which dynamically create and populate a number of tables in MySQL Server Version 5.5.

When I do this, I am logging the SQL to an Apache Tomcat log file. Sometimes the SQL listings
will list a particular series of queries reading the <title> elements of RSS feeds one by one such as:

SELECT TITLE FROM _rss_172_917617_01012011_1293889632011 WHERE CreatedDateTime BETWEEN '2011-07-01 00:00:00' AND '2011-07-31 23:59:00';
SELECT TITLE FROM _rss_173_353205_01012011_1293889643042 WHERE CreatedDateTime BETWEEN '2011-07-01 00:00:00' AND '2011-07-31 23:59:00';

Then the name of the system will be printed as follows in the log file:

[myApp]

And then there will be a series of lines reading:

545

Before the next series of queries run. And when the next series of queries does run, the text of each query is listed, and then another line lists the system name.

SELECT TITLE FROM _rss_121_298920_24122010_1293174184748 WHERE CreatedDateTime BETWEEN '2011-07-01 00:00:00' AND '2011-07-01 23:59:00';
[myApp]

MyApp is written in Java and running under Tomcat 6.0.26. I should add that sometimes the number of queries producing the data for one table, which may number in the hundreds, appear to be fine. Other times the 545 message is listed: this appears to be sporadic with no apparent pattern.

Though the queries appear to be running, can anyone tell me what 545 might mean? It seems to happen on two separate servers running the same programs but with different data.

This query is also posted in the Newbie forum. Apologies for any inconvenience.

Why does JDBC application logging SQL instructions in Apache Tomcat lists 545 repeatedly (1 reply)

$
0
0
I'm currently running a number of programs in batch which dynamically create and populate a number of tables in MySQL Server Version 5.5.

When I do this, I am logging the SQL to an Apache Tomcat log file. Sometimes the SQL listings
will list a particular series of queries reading the <title> elements of RSS feeds one by one such as:

SELECT TITLE FROM _rss_172_917617_01012011_1293889632011 WHERE CreatedDateTime BETWEEN '2011-07-01 00:00:00' AND '2011-07-31 23:59:00';
SELECT TITLE FROM _rss_173_353205_01012011_1293889643042 WHERE CreatedDateTime BETWEEN '2011-07-01 00:00:00' AND '2011-07-31 23:59:00';

Then the name of the system will be printed as follows in the log file:

[myApp]

And then there will be a series of lines reading:

545

Before the next series of queries run. And when the next series of queries does run, the text of each query is listed, and then another line lists the system name.

SELECT TITLE FROM _rss_121_298920_24122010_1293174184748 WHERE CreatedDateTime BETWEEN '2011-07-01 00:00:00' AND '2011-07-01 23:59:00';
[myApp]

MyApp is written in Java and running under Tomcat 6.0.26. I should add that sometimes the number of queries producing the data for one table, which may number in the hundreds, appear to be fine. Other times the 545 message is listed: this appears to be sporadic with no apparent pattern.

Though the queries appear to be running, can anyone tell me what 545 might mean? It seems to happen on two separate servers running the same programs but with different data.

This query is also logged in the JDBC forum. Apologies for inconvenience.

SP to output Updated value with a multithreaded java client (no replies)

$
0
0
I have a SP in Mysql , which selects a value from a table and sends it out. Then adds 1 to the value and updates the table. something i tried to emulate Oracle Sequence. The issue is this SP is called from Java Multithread program Each time it gives the same value to all the threads

CLarify my how to tackle this is there anything we can do that in MYsql or is it be handled in Java. I am not a Java resource

Problem with long unique index (no replies)

$
0
0
In my Java application, I connect to my database like this:

Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/db?useServerPrepStmts=false&rewriteBatchedStatements=true",
"myuser","mypass");

create a table like this:

java.sql.Statement createSt = conn.createStatement();
createSt.executeUpdate(String.format("CREATE TABLE IF NOT EXISTS %s.%s ( "
+ "id INT NOT NULL AUTO_INCREMENT,"
+ "res1 VARCHAR(255) NULL ,"
+ "res2 VARCHAR(255) NULL ,"
+ "similarity DOUBLE NULL ,"
+ "PRIMARY KEY (id) ,"
+ "UNIQUE INDEX bothres (res1, res2) ,"
+ "INDEX (similarity) )", dbName, tableName));
Create a prepared statement:

PreparedStatement pst = conn.prepareStatement(String.format("INSERT INTO %s.%s values (default, ?, ?, ?)", dbName, tableName));

And then insert data in batches like this:

public void insert(String uri1, String uri2, double sim){
pst.setString(1, uri1);
pst.setString(2, uri2);
pst.setDouble(3, simil);
pst.addBatch();
if(++batchCount%maxBatch == 0){
pst.executeBatch();
}
}

The uri1 and uri2 Strings are simply urls like http://xmlns.com/foaf/0.1/Document or http://xmlns.com/foaf/0.1/Person
or any other URI.
Even though I am 100% sure that the insert method is never called with the same pair of URIs, on executeBatch() an
BatchUpdateException - Duplicate entry 'http://reference.data.gov.uk/def/intervals/Minute-http://bio2rdf' for key 'bothres'
is thrown.
That is weird to me is the fact that the second uri is always truncated, as if the database would not store it completely. Is the length of such keys limited, and if so, how can I increase the length?

Int the example above, the error is likely caused because I am calling insert several times with
uri1 = "http://reference.data.gov.uk/def/intervals/Minute&quot;
and uri2 = "http://bio2rdf/foo/uri1&quot;, uri2 = "http://bio2rdf/foo/uri2&quot;, etc. but never with the exact same uris.

I found that InnoDB index key prefixes have limited length, but I am not sure if this is the issue here. I set
innodb_large_prefix=true
innodb_file_format=Barracuda
innodb_file_per_table=1
in my.cnf, but this doesnt help.

If anyone can give me a hint how to resolve this, I would be very thankful!

Connector/J 5.1.26 for windows 7 64 bit (1 reply)

$
0
0
Need window7 64 bit for Connector/J 5.1.26. thx.

How to select product category even it has zero sales volume? (1 reply)

$
0
0
String str = "SELECT S.ProductName,"
                + " S.items_total_sales AS 'Total Sales'" // each product sum of sales by money so sum
                + " from"
                    + " ((SELECT products.ProductName, "
                    + " sum(products.UnitPrice * order_details.Discount * order_details.Quantity) AS items_total_sales "
                    + " from (products AS products "
                    + " RIGHT JOIN order_details AS order_details ON (products.ProductID = order_details.ProductID))"
                    + " GROUP BY products.ProductName) AS S) ";
Some products with zero sales are not shown here
Thanks
Jack

Urgent please help Ignore Space after function name (no replies)

$
0
0
Hi

I am Prashant I am using PowerBuilder 11.5 and MySQL 5.1 on Windows 7 32 Bit. PowerBuilder Application required Optional prameter IGNORE_SPACE Ignore space after function names 4096 Tell server to ignore space after function name and before “(” (needed by PowerBuilder). This makes all function names keywords.

Previously i was using ODBC Driver there we do have Option in the form of checkbox to set this option.

Now i am trying to connect using JDBC driver i sucesfully connect to MySQL but the problem is whenever is used any function like sum() or count() it give PowerBuilder error
Database C0038: SQLSTATE = 42000 You have an error in SQL syntax; check the manual for corrosponding to your MySQL server version for the right syntax to use near '*) from my_table' at line 1

you will get more info on
http://dev.mysql.com/doc/refman/5.0/es/myodbc-configuration-connection-parameters.html
http://dev.mysql.com/doc/refman/5.5/en/connector-odbc-configuration-connection-parameters.html#codbc-dsn-option-flags

since i am new to this please help i am in great trouble.

my connection parametrs are as follows
// Profile Transporter3
SQLCA.DBMS = "JDBC"
SQLCA.LogPass = "tss"
SQLCA.LogId = "root"
SQLCA.AutoCommit = False
SQLCA.DBParm = "Driver='com.mysql.jdbc.Driver',URL='jdbc:mysql://localhost:3306/mydb'"

aes_encrypted string doesn't match original after aes_decrypt (no replies)

$
0
0
Hi All,

I'm trying to convert a bunch of passwords in my DB from one encryption method (DES) to another (AES). What I'm finding is that I can decrypt the original string, re-encrypt it using aes_encrypt (via a function call) but if I then call aes_decrypt I don't always get back the original string. Here are some code snippets:

public static final String AES_KEY = "mf3OIRkLFe2xLuPIARGHnCHzzuGb4Rnh4Qp9DKKn8qkyRjCT";

Encrypt method:
String stmt = "{? = CALL AES_ENCRYPT(?, ?)}";
CallableStatement cstmt = conn.prepareCall(stmt);
cstmt.setString(2, clearString);
cstmt.setString(3, AES_KEY);
cstmt.registerOutParameter(1, Types.VARBINARY);
cstmt.execute();
byte[] varbinary = cstmt.getBytes(1);
String encString = new String(varbinary);
return encString;

Decrypt method:
String stmt = "{? = CALL AES_DECRYPT(?, ?)}";
CallableStatement cstmt = conn.prepareCall(stmt);
cstmt.setString(2, str);
cstmt.setString(3, AES_KEY);
cstmt.registerOutParameter(1, Types.VARCHAR);
cstmt.execute();
String clearString = cstmt.getString(1);
return clearString;

I've tried several different key lengths (multiples of 8 chars) and varieties, including sending the key as a String or a Byte array.
Roughly 20% of my strings won't decrypt correctly but it's never the same 20% depending on which key I use.

I would like to use the aes function calls as a PHP process will be creating my users rows with their passwords.

Any help is greatly appreciated!
TIA... Chris

driver connection (no replies)

$
0
0
HI all,
I have netbeans ide 7.3.1 installed.
i have mysql 5.5 installed.
i have a problem in designing jsp web applications with mysql database connection.
when i write in jsp the following code:
Class.forName("com.mysql.jdbc.Driver");
i get the error class not found.

is thr any setting to be done or any file to be added anywhere to get the driver identified??

i have done all database settings in netbeans ide LIke registering mysql, creating database, creating driver.

bt still errors..pls help??????????

mysql database driver in netbeans ide (no replies)

$
0
0
hi all,

i have netbeans ide 7.3.1 installed and mysql5.5 too.
i am getting error while getting to mysql database driver.
i have done all setting in databases from netbeans like configuring mysql,creating driver,creating a database. etc.

but when i write my jsp file, i get the error for the following line:
Class.forName("com.mysql.jdbc.Driver");

it says class not found. wherein the driver is created and is indicating the above name.


what can be the error?????? pls help.......

Java 7/JDBC 4.1 and Java 8/JDBC 4.2 (no replies)

$
0
0
It has now been 2 years, 1.5 months since Java 7 / JDBC 4.1 was released. This maintenance release contained some minor, though still useful, revisions to JDBC that are unusable in MySQL because the MySQL driver only supports JDBC 4.0.

Now Java 8 / JDBC 4.2 is just around the corner (final public release candidate in January, GA in early March). It contains some very important updates, including (most importantly to me) support for the new Java 8 Date & Time API types (java.time JSR 310).

What is the time frame for getting a release that supports JDBC 4.1 and then a release for JDBC 4.2? JDBC 4.1 should have been available a long time ago. I really hope I don't have to wait 2 or 3 more years for JDBC 4.2 support...
Viewing all 884 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>