How to set auto-increment the numbers in mysql workbench with a character prefix by using netbeans - netbeans

How to increment the numbers in mysql with a character prefix using netbeans
A1-01
A1-02
A1-03
AND
A2-01
A2-02
A2-02
I had try this as below mentioned
try {
Class.forName("com.mysql.cj.jdbc.Driver");
sqlConne = DriverManager.getConnection(dataConn, username, password);
st = sqlConne.createStatement();
for (int i = 0; i < model.getRowCount(); i++) {
int id = Integer.valueOf(model.getValueAt(i, 0).toString());
String Status = jTextField_status.getText();
String zonevalue = jTextField1.getText();
String space = jTextField2.getText();
String updateQuery = "UPDATE master_data SET status='" + Status + "', zone_spacevalue='" + transfer_zonename.concat(zonevalue) + "' WHERE s_no = " + id;
st.addBatch(updateQuery);
int insertResult = st.executeUpdate(updateQuery);
if (insertResult > 0) {
insertedResult++;
}
}
int[] updatedRow = st.executeBatch();
System.out.println(updatedRow.length);
catch (SQLException ex) {
Logger.getLogger(assign_data.class.getName()).log(Level.SEVERE, null, ex);
catch (ClassNotFoundException ex) {
ex.printStackTrace();
}
and i want that zone wise allocation item with autoincrement number like warehouse allocation system

Related

Values not inserted in table

I have company table where values are inserted
public int SaveCompany(Company objCompany)
{
int CompanyID = 0
try
{
using (var context = new Cubicle_EntityEntities())
{
context.Companies.Add(objCompany); //add entity to the add method
int res = context.SaveChanges(); //insert it into table
if (res > 0)
{
Debug.WriteLine("Data Inserted Successfully");
}
else
{
Debug.WriteLine("Try Again");
}
CompanyID = objCompany.CompanyId;
Debug.WriteLine("CompanyId " + CompanyID);
}
}
catch (Exception ex)
{
CompanyID = 0;
bool rethrow = UserInterfaceExceptionHandler.HandleException(ref ex);
throw ex;
}
return CompanyID;
}
Every time I get res 1,but data not inserted in table.

How select random documents in OrientDB

I write online game. For game logic, I need select random users(etc) from database. How to achive this with java api? What the most perfomance way to do this?
I can use something like(pseudocode): select from User skip(randomNum(0,usersCount)) limit 1 but how write in documentation - skip has bad performance.
I have tried with this code
int numberRandom= 5;
String string="[";
int cluster= db.getMetadata().getSchema().getClass("User").getClusterIds()[0];
for(int i=0;i<numberRandom;i++){
int random=ThreadLocalRandom.current().nextInt(0, 96000);
if(i==(numberRandom-1))
string += cluster+":"+random + "]";
else
string += cluster+":"+random + ",";
}
Iterable<Vertex> result = g.command(new OCommandSQL("select from "+ string)).execute();
for(Vertex v:result)
System.out.println(v.getId());
Let me know if it can be a good solution for you
I wrote two java classes, both are getting X random users from a specific cluster.
The first one seams faster to me. (about 0.8s vs 1.2s)
testRandom.java
public class testRandom {
public static void main(String[] args) {
// TODO Auto-generated method stub
String nomeDb = "RandomUser";
try {
OServerAdmin serverAdmin = new OServerAdmin("remote:localhost/"+nomeDb).connect("root", "root");
if(serverAdmin.existsDatabase()){ // il db esiste
//connessione a db
OrientGraph g = new OrientGraph("remote:localhost/"+nomeDb);
//------------------------------------------------
long Tbegin,Tend;
float millis;
Tbegin = System.currentTimeMillis();
int numberRandom= 5;
int random;
String cluster = "user";
Iterable<Vertex> vertices = g.command(new OCommandSQL("select from cluster:"+cluster)).execute();
List<Vertex> v_array = new ArrayList<Vertex>();
List<Vertex> res = new ArrayList<Vertex>();
for(Vertex v : vertices){
v_array.add(v);
}
int arraysize = v_array.size();
for(int i=0;i<numberRandom;i++){
random=ThreadLocalRandom.current().nextInt(0, arraysize);
res.add(v_array.get(random));
}
for(Vertex v : res){
System.out.println(v.getId());
}
Tend = System.currentTimeMillis();
millis = (Tend-Tbegin);
System.out.println("--Execution time: "+millis/1000+ "s\n");
//------------------------------------------------
//chiude db
g.shutdown();
}
else{
System.out.println("Il database '"+ nomeDb + "' non esiste");
}
serverAdmin.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
testRandomSkip.java
public class testRandom_skip {
public static void main(String[] args) {
// TODO Auto-generated method stub
String nomeDb = "RandomUser";
try {
OServerAdmin serverAdmin = new OServerAdmin("remote:localhost/"+nomeDb).connect("root", "root");
if(serverAdmin.existsDatabase()){ // il db esiste
//connessione a db
OrientGraph g = new OrientGraph("remote:localhost/"+nomeDb);
//------------------------------------------------
long Tbegin,Tend;
float millis;
Tbegin = System.currentTimeMillis();
int numberRandom= 5;
int random;
String cluster = "user";
List<Vertex> res = new ArrayList<Vertex>();
Iterable<Vertex> q_count_V = g.command(new OCommandSQL("select count(*) from cluster:"+cluster)).execute();
Long count_V = 0l;
for(Vertex v : q_count_V){
count_V=v.getProperty("count");
break;
}
for(int i=0;i<numberRandom;i++){
random=(int)ThreadLocalRandom.current().nextLong(0, count_V);
Iterable<Vertex> vertex = g.command(new OCommandSQL("select from cluster:"+cluster+" skip "+random+" limit 1")).execute();
for(Vertex v : vertex){
res.add(v);
break;
}
}
for(Vertex v : res){
System.out.println(v.getId());
}
Tend = System.currentTimeMillis();
millis = (Tend-Tbegin);
System.out.println("--Execution time: "+millis/1000+ "s\n");
//------------------------------------------------
//chiude db
g.shutdown();
}
else{
System.out.println("Il database '"+ nomeDb + "' non esiste");
}
serverAdmin.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Hope it helps.
Ivan

Titan Key with given name does not exist

I create two indexes but when I want to invoke vertex.setProperties(), my program prompts with "given name does not exist.". Below is my code:
initDB
public void tstInitHBase() {
Configuration conf = new BaseConfiguration();
conf.setProperty("storage.backend", "hbase");
conf.setProperty("storage.hostname", "192.168.22.209");
conf.setProperty("storage.port", "2181");
conf.setProperty("storage.tablename", "social_map");
conf.setProperty("cache.db-cache", "true");
conf.setProperty("cache.db-cache-clean-wait", "20");
conf.setProperty("cache.db-cache-time", "180000");
conf.setProperty("cache.db-cache-size", "0.5");
GraphDatabaseConfiguration graphconfig = new GraphDatabaseConfiguration(conf);
try {
graphconfig.getBackend().clearStorage();
} catch (StorageException e) {
e.printStackTrace();
throw new RuntimeException("Techvalley:ERROR 清空数据库失败");
}
TitanGraph graph = TitanFactory.open(conf);
graph.makeKey("PKID").dataType(String.class).indexed(Vertex.class).unique(UniquenessConsistency.LOCK).make();
graph.makeKey("CN_NAME").dataType(String.class).indexed(Vertex.class).make();
graph.makeKey("EDGE_PEERS_WEIGHT").dataType(Long.class).indexed(Edge.class).make();
graph.commit();
}
Insert Data with pig
//objList structure is like (uuid,cn_name,gender,..)
vertex = tx.getVertex(DataType.toString(objList.get(0)));
if (vertex == null) {
logger.info("create node");
vertex = tx.addVertex(DataType.toString(objList.get(0)));
vertex.setProperty(flied[0], DataType.toString(objList.get(0)));
}
/**
*
* */
for (int i = 1; i < flied.length; i++) {
switch (DataType.findType(objList.get(i))) {
case DataType.NULL:
logger.info("cache" + flied[i] + " " + DataType.toString(objList.get(i)));
ElementHelper.setProperties(vertex, flied[i],DataType.toString(objList.get(i)));
break;
case DataType.CHARARRAY:
logger.info("cache" + flied[i] + " " + DataType.toString( objList.get(i)));
ElementHelper.setProperties(vertex, flied[i],DataType.toString(objList.get(i)));
break;
default:
break;
}
}
When I execute ElementHelper.setProperties(vertex,flied[i],DataType.toString(objList.get(i))); my program always returns 'Key with given name does not exist'.
Any ideas?
Find out the offending property key by wrapping ElementHelper.setProperties in try/catch and logging/printing the property key name. Then add it to the graph.makeKey set.

In what order C# execute sqlstatement?

I have two table related by foreign and primary key constraint.The Visit_Number in Patient table must exist in the Visit table.In my code in define create two instance of my connection string such that i can use one instance to insert record:VisitNumber in Visit table first and then the other instance to insert record in the patient table,with the believe that the cord runs from top to bottom.But this was n't the case. i still get foreign key constraint errror:
Error Number:547
Error MessageThe INSERT statement conflicted with the FOREIGN KEY constraint "Patient_Vist_FK".
The conflict occurred in database "TestDB", table "dbo.Visit", column 'Visit_Number'.
The statement has been terminated.On line Number: 1
meaning the code is running as i expected. Please do you have a better approach and why isn't mine working
code:
protected void btn_save_Click(object sender, EventArgs e)
{
string connect = System.Configuration.ConfigurationManager.ConnectionStrings["db_connection"].ToString();
SqlConnection con = new SqlConnection(connect);
SqlConnection con2 = new SqlConnection(connect);
string visitnumber = txtVistNumber.Text.ToString();
string insert_statement = "Insert into Patient(Patient_Number,FirstName,LastName,Gender,Tribe,Date_Of_Birth,Visit_Number)"
+ "Values(#Patient_Number,#FirstName,#LastName,#Gender,#Tribe,#Date_Of_Birth,#Visit_Number)";
string insert_stament2 = "Insert into Visit(Visit_Number)"
+ "Values(#Visit_Number)";
SqlCommand cmd = new SqlCommand(insert_statement, con);
SqlCommand cmd2 = new SqlCommand(insert_stament2, con2);
cmd2.Parameters.AddWithValue("#Visit_Number", txtVistNumber.Text);
cmd.Parameters.AddWithValue("#Patient_Number",txtpatientNum.Text);
cmd.Parameters.AddWithValue("#FirstName",txtfirstName.Text);
cmd.Parameters.AddWithValue("#LastName",txtlastname.Text);
cmd.Parameters.AddWithValue("#Gender", drl_gender.SelectedValue);
cmd.Parameters.AddWithValue("#Tribe",DropDownList1.Text);
cmd.Parameters.AddWithValue("#Date_Of_Birth", val_age.Text);
cmd.Parameters.AddWithValue("#Visit_Number", txtVistNumber.Text);
try
{
using (con)
{
con.Open();
int count = cmd.ExecuteNonQuery();
if (count > 0)
{
Response.Write("<script language=javascript>alert('Record Sucessfully Inserted!');</script>");
//Success_Message.Text = "Record inserted";
txtpatientNum.Text = String.Empty;
txtfirstName.Text = String.Empty;
txtlastname.Text = String.Empty;
txtVistNumber.Text = String.Empty;
DropDownList1.Text = String.Empty;
val_age.Text = String.Empty;
}
}
}
catch (SqlException ex)
{
{
VisitError_Message.Text = "Error Number:" + ex.Number.ToString() + " Error Message" + ex.Message + "On line Number" + ": " + ex.LineNumber;
}
}
catch (NullReferenceException nullexception)
{
VisitError_Message.Text = "Error Occurred, Error Type:" + nullexception.GetType().ToString() + "Error Message:" + nullexception.Message;
}
catch (DllNotFoundException dllexception)
{
VisitError_Message.Text = dllexception.GetType().ToString() + dllexception.Message;
}
finally
{
con.Close();
}
}
you not excuting you cmd2, you must execute the insert Visit_Number in cmd2 then excute your cmd, you can test this code
using (con2)
{
con2.Open();
cmd2.ExecuteNonQuery();
}
then you can excute your cmd
using (con)
{
con.Open();
int count = cmd.ExecuteNonQuery();
}
and you can do the work with the same connexion if you want
string connect = System.Configuration.ConfigurationManager.ConnectionStrings["db_connection"].ToString();
SqlConnection con = new SqlConnection(connect);
string visitnumber = txtVistNumber.Text.ToString();
string insert_statement = "Insert into Patient(Patient_Number,FirstName,LastName,Gender,Tribe,Date_Of_Birth,Visit_Number)"
+ "Values(#Patient_Number,#FirstName,#LastName,#Gender,#Tribe,#Date_Of_Birth,#Visit_Number)";
string insert_stament2 = "Insert into Visit(Visit_Number)"
+ "Values(#Visit_Number)";
using(con)
{
con.open;
SqlCommand cmd2 = new SqlCommand(insert_stament2, con);
cmd2.Parameters.AddWithValue("#Visit_Number", txtVistNumber.Text);
cmd2.ExecuteNonQuery();
SqlCommand cmd = new SqlCommand(insert_statement, con);
cmd.Parameters.AddWithValue("#Visit_Number", txtVistNumber.Text);
cmd.Parameters.AddWithValue("#Patient_Number",txtpatientNum.Text);
cmd.Parameters.AddWithValue("#FirstName",txtfirstName.Text);
cmd.Parameters.AddWithValue("#LastName",txtlastname.Text);
cmd.Parameters.AddWithValue("#Gender", drl_gender.SelectedValue);
cmd.Parameters.AddWithValue("#Tribe",DropDownList1.Text);
cmd.Parameters.AddWithValue("#Date_Of_Birth", val_age.Text);
cmd.Parameters.AddWithValue("#Visit_Number", txtVistNumber.Text);
cmd.ExecuteNonQuery();
}

Why "SELECT DISTINCT" with HSQLDB not working?

I have a problem. When I try to use the "Select distinct" in HSQLDB, the stream of results returns me all rows instead of me returning only distinct rows.
I've tried the following syntax:
SELECT DISTINCT FROM ratings UserID order by UserID;
SELECT DISTINCT (UserID) FROM ratings order by UserID;
SELECT DISTINCT UserID FROM ratings;
SELECT DISTINCT (UserID) FROM ratings;
None of them works. What is the problem?
If anyone able to help me I appreciate.
Thank you.
The function code where I perform the action is as follows:
private void readUserFile(String filename) {
try {
//Verify if file users exists
boolean exists = (new File(filename)).exists();
if (!exists) {
//If file users not exists create one, bases on distinct users that exist in ratings table
ResultSet rsUsers = jdbcTemplate.getDataSource().getConnection().createStatement().executeQuery("SELECT DISTINCT UserID FROM ratings order by UserID;");
List<String> users = new ArrayList<String>();
while (rsUsers.next()) {
users.add(String.valueOf(rsUsers.getInt(1)));
}
rsUsers.close();
//Create and write to file
BufferedWriter f = null;
f = new BufferedWriter(new FileWriter(filename));
for (String user : users) {
f.write(user);
f.newLine();
}
f.close();
}
PreparedStatement prstInsert = con.prepareStatement("INSERT INTO users VALUES (?)");
BufferedReader in = new BufferedReader(new FileReader(filename));
int i = 0;
while (true) {
String s = in.readLine();
if (s == null) { // end of file
log.info("Total imported users: " + i);
break;
}
i++;
int userid = Integer.parseInt(s);
prstInsert.setInt(1, userid);
if (i != 0 && Math.round((double) i / 100) == ((double) i / 100)) {
log.info("Imported users: " + i);
}
prstInsert.executeUpdate();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}